Can constructor inherited
Answer : A constructor cannot be inherited and since in subclasses it has a different name (that is name of the subclass). Please see example below:
Important point:
- It makes more sense to inherit a constructor
- Constructor of class A means creating an object of type ConstructorTest2
- Constructor of class B means creating an object of class ConstructorTest
- Call sequence will be invoke superclass contructor then subclass constructor
Please see example below:
package com.javahonk.thistest; public class ConstructorTest extends ConstructorTest2 { // constructor declared public ConstructorTest() { System.out.println("subclass constructor"); } public static void main(String args[]) { //invoke super class empty consturctor first //invode subclass empty constructor ConstructorTest constructorTest = new ConstructorTest(); //invoke super class empty consturctor first //invode subclass empty constructor ConstructorTest2 constructorTest2 =new ConstructorTest(); //Not possible //ConstructorTest constructorTest3=new ConstructorTest2(); } } class ConstructorTest2 { ConstructorTest2() { System.out.println("superclass constructor"); } }
Output: