is constructor inherited in java?

Constructor

Constructor is a block of statements that permits you to create an object of specified class and has similar name as class with no explicit  or specific return type.

No, constructor cannot be inherited in java.

In case of inheritance, child/sub class inherits the state (data members) and behavior (methods) of parent/super class. But it does not inherits the constructor because of the following reason:

If parent class constructor is inherited in child class, then it can not be treated as constructor because constructor name must be same as of class name. It will be treated as a method but now the problem is, method should have explicit return type which inherited parent class constructor can not have. Example

class SuperClass { 
    public SuperClass() 
    { 
        System.out.println("SuperClass constructor.");
    } 
 
    public void show() 
    { 
         System.out.println("SuperClass method.");
    } 
} 
 
public class SubClass extends SuperClass { 
 
    public static void main(String[] args) 
    { 
        SubClass object1 = new SubClass(); // allowed 
        object1.show(); // allowed
        object1.SuperClass(); // not allowed
        SubClass object2 = new SuperClass(); // not allowed 
    } 
}

Output

SubClass.java:27: error: cannot find symbol
        object1.SuperClass(); // not allowed
               ^
  symbol:   method SuperClass()
  location: variable object1 of type Main
SubClass.java:28: error: incompatible types: SuperClass cannot be converted to Main
        SubClass object2 = new SuperClass(); // not allowed 
                       ^
2 errors

Java interview questions on constructor

Please follow and like us:
Content Protection by DMCA.com