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);
  

}

6 comments:

  1. Awesome post.
    I read your blog everything is helpful and effective.
    Thanks for sharing with us.
    Web Designing Training in Chennai

    ReplyDelete
  2. Conservatrader Software License

    https://Silverstarbuilder.com/join/?sponsor=bnicebethyname&rt=c

    Join – Silver Star Live - Silver Star Live is an educational and trading platform providing cutting edge wealth creation services worldwide.

    ReplyDelete
  3. Its a wonderful post and very helpful, thanks for all this information.
    Java Training in Delhi

    ReplyDelete
  4. Thanks for sharing this kind of information. it is very helpful to the beginers and very intresting to read i never heard before like this type of article keep blogging...
    Hadoop Training In Hyderabad
    Tableau Training In Hyderabad

    ReplyDelete