Powered By Blogger

Monday, March 12, 2012

Constructors and inheritance in Java

While methods of the superclass are inherited to the subclass, this is not the case with constructors.
Constructors are never inherited in Java. If you do not define a constructor for a class that extends another
class with one or more constructors defined, a default constructor will be generated for the subclass.
However, what you can do is call the constructor of the superclass from the  subclass (using super).

For instance, you cannot do the following:
class Nature {

  
String name;

  
Nature () {
  }
  
  Nature (String name) {
    this.name = name;
  }
}

class Tree extends Nature {

  /* No constructor defined for this class. 
  The compiler generates the default constructor 
  with zero arguments    */
 }

class Pinetree extends Tree {

  
Pinetree (String name) {
    // ERROR: Cannot do this
    // super(name);
  

}