aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructor? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructor?" Watch "Constructor?" New topic
Author

Constructor?

Gary Kevin
Ranch Hand

Joined: Jul 24, 2006
Posts: 43
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?


SCJP 5.0 72%
Viorel Craescu
Greenhorn

Joined: Apr 21, 2008
Posts: 26
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

Joined: Dec 08, 2004
Posts: 8
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'.
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

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.


Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
Gary Kevin
Ranch Hand

Joined: Jul 24, 2006
Posts: 43
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()?

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Constructor?