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
- Default constructor
- Does constructor return any value in java?
- Is constructor inherited in java?
- Can you make a constructor final in java?
- Difference between constructor and method in java?
- How to copy values from one object to another java?
- How to overload constructor in java?
- can you create an object without using new operator in java?
- Constructor chaining in java
- Parameterized constructor in java
- Can we call subclass constructor from superclass constructor?
- What happens if you keep return type for a constructor?
- What is the use of private constructor in java?
- Can a constructor call another constructor java?