Java Object Creation of Inherited Class

Java 8Object Oriented ProgrammingProgramming

In java constructor is something which is responsible for object creation of a particular class.Along with other functions of constructor it also instantiate the properties/instances of its class.In java by default super() method is used as first line of constructor of every class,here the purpose of this method is to invoke constructor of its parent class so that the properties of its parent get well instantiated before subclass inherits them and use.

The point that should remember here is when you create a object the constructor is called but it is not mandatory that whenever you called a constructor of a class an object of that class is created.As in above case the construcotr of parent is called from constructor of sub class but object of subclass is created only,as subclass is in is-a relation with its parent class.

Example

 Live Demo

class InheritanceObjectCreationParent {
   public InheritanceObjectCreationParent() {
      System.out.println("parent class constructor called..");
      System.out.println(this.getClass().getName()); //to know the class of which object is created.
   }
}
public class InheritanceObjectCreation extends InheritanceObjectCreationParent {
   public InheritanceObjectCreation() {
      //here we do not explicitly call super() method but at runtime complier call parent class constructor
      //by adding super() method at first line of this constructor.
      System.out.println("subclass constructor called..");
      System.out.println(this.getClass().getName()); //to know the class of which object is created.
   }
   public static void main(String[] args) {
      InheritanceObjectCreation obj = new InheritanceObjectCreation(); // object creation.
   }
}

Output

parent class constructor called..
InheritanceObjectCreation
subclass constructor called..
InheritanceObjectCreation
raja
Published on 01-Nov-2018 10:58:29
Advertisements