It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overloading constructors. 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 "Overloading constructors." Watch "Overloading constructors." New topic
Author

Overloading constructors.

Vicken Karaoghlanian
Ranch Hand

Joined: Jul 21, 2003
Posts: 522
providing this statement:

if the superclass contains a constructor that has arguments, Java will not create a default constructor for any subclasses that are created.

now check this code:

the previous rule stated clearly that the constructor test() with no arguments will not be created, therfore there will be no implicit call to the non-argument constructor of the super class (test2), making this code compile.
BUT for a strange reason this is not the case. any ideas why?


- Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth. - What truth? - That there is no spoon!!!
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
The rule is wrong. The compiler will not create a default constructor for a class already declaring a constructor.


SCJP2. Please Indent your code using UBB Code
Muzammil Khan
Greenhorn

Joined: Jul 22, 2003
Posts: 8
Hi Vicken Karaoghlanian,
Let us assume we have superclass and a subclass as follows:

When a new instance of FourWheeler is created as follows:
FourWheeler fourWheeler = new FourWheeler();

FourWheeler defines no constructors, however, FourWheeler is extended from Vehicle, and Vehicle does have a constructor that needs to be invoked for the instance of B. How does this work?
What happens is as follows:
1) A default constructor is generated automatically
2) The constructor calls the superclass constructor with no arguments.
So "new FourWheeler()" results in
1) The generated default constructor for FourWheeler being called
2) It in turn calls the no-argument constructor for Vehicle.
3) The generated constructor is given the access modifier "public" if the class is public, or else the constructor is given the default access implied by no modifier.
In other words, a constructor for Vehicle is generated, and it simply invokes the superclass of Vehicle, which in this case is java.lang.Object constructor.
Tip
Relying on default constructor generation is not a good programming practice. You can control class instantiation by means of protected or private constructors making it uninstantiable.
Hope this helps.
Muzz
MSC Computing
NOTHING WORTH WHILE WILL EVER BE ACHIEVED WITHOUT DEEP THOUGHT AND HARDWORK - J.R.D TATA


Muzz<br />MSC Computing<br />Nothing worth while will ever be achieved without DEEP THOUGHT AND HARDWORK - J.R.D TATA
 
GeeCON Prague 2014
 
subject: Overloading constructors.