• Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling constrctor vs calling method  RSS feed

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello

I did this code to display the constructor and two methods.



However the output I get is

This is a constructor
This is a constructor
This is a method 1
This is a constructor
This is a method 2



Now the program is displaying the constructor 3 times? Is there a way to call a method without calling the constructor again ??
As if I want the output to be like this

This is a constructor
This is a method 1
This is a method 2


Can someone help me ?

 
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The program displays "This is a constructor" three times because you are creating three objects - you are calling new cls() three times.

Ofcourse there is a way to call a method without calling the constructor again. Just call the method on the same object that you already created. For example:

Note: You are not really calling the constructor. You can't call constructors directly. Java will call the constructor when you create a new object using the new operator.
 
Sheriff
Posts: 4935
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And have in mind, that java Class names suppose to start with an Upper case as well as Constructor names.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!