Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor?

 
Gary Kevin
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
source:http://enigma.vm.bytemark.co.uk/webstart.html
John Meyers's SCJP 5 mock exam:question 60




A prints 2
B prints 0
C Does not compile
D Runtime Exception
E None of above

The correct answer is C.
This invocation will searh for a function named test. It does not invoke the overloaded test() constructor

why it compiles false at line 9?
 
Viorel Craescu
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because you can't access the constructor like this.


Constructors are invoked inside the class using this() or super() (for superclass constructor). When you are trying to invoke it as you did, then the compiler is looking for a method named test which takes one argument. Can't find it and throw an error. So you don't actually invoke the constructor, you actually invoke a method which takes one int argument.
If you replace test(2) with this(2) the code will compile.

Viorel
 
Anu Kalra
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Gary,
The reason it won't compile is that the jvm looks for the method test(int) in the class, but does not get it (Since you dont have it!)
If you would like to call the constructor, you have to use 'this'.
 
Deepak Chopra
Ranch Hand
Posts: 433
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with both, putting in simple words, there are two cases when compiler will invoke constructor:

Case 1:
when it encounter new keyword, in this case it will call the constructor of the class, through which you are trying to create an object

Case 2:
When it encounter this() or super().

there is no way you can directly write down the name of constructor and call it. hope it will help you.
 
Gary Kevin
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Viorel Craescu:
Because you can't access the constructor like this.


Constructors are invoked inside the class using this() or super() (for superclass constructor). When you are trying to invoke it as you did, then the compiler is looking for a method named test which takes one argument. Can't find it and throw an error. So you don't actually invoke the constructor, you actually invoke a method which takes one int argument.
If you replace test(2) with this(2) the code will compile.

Viorel




Viorel:

I know that the JVM will insert this() or super() to the first line of constructor.But under which conditions the JVM  insert this()? or super()?

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic