• Post Reply Bookmark Topic Watch Topic
  • New Topic

putting void in the class constructor cause problem, why ?  RSS feed

 
raymond hsu
Greenhorn
Posts: 23
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I try to experiment class variable in a very simple java code,
I know that class constructor don't return value by default, but if I put explicitly a 'void' , the constructor doesn't seem to have executed, does anyone know why ?
if i remove the void, it will work as expected, i.e. returns a value of 12.


result of output when running callingclass is

C:\JAVAPR>java callingclass
public class var int in calledclass is 10
after increment by 1, public class var int in calledclass is 11
after new calledclass, public class var int in calledclass is 11
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66207
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constructors do not have return types. If you add one, it's no longer a constructor, so it doesn't work.
 
raymond hsu
Greenhorn
Posts: 23
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bear Bibeault for the answer.

Bear Bibeault said in line 4, calledclass is not treated as a constructor because it
specifically mention a type which is void, i.e. no return value.

since compilation results in no error, so I thought calledclass must be treated as
an instance method within the class calledclass.
From the book 'Java all-in-one for dummies', I learnt that the compiler will create a
default constructor for a class when it can't find any in the class.
The default constructor will do nothing except to allow an instance of the
class to be created.
I guess that's the reason why when I create an instance of calledclass,
the variable remains at the value of 11.

I then added 2 additional line of code at the end of main() method

this time the command window output is

public class var int in calledclass is 10
after increment by 1, public class var int in calledclass is 11
after new calledclass, public class var int in calledclass is 11
inside addintby1 routine, after increment by 1 again, publicclassvarint is 12
after calling calledclass as a instance method, public class var int is 12

this confirms that compiler has interpreted calledclass as an instance method in class
calledclass.

thank you for the help.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!