Can a constructor be overridden in java?


If super class and sub class have same methods including name, return type and parameters, and if you try to call it using the object of the sub class

Then the method in the sub class is invoked.

Constructor looks like method but it is not. It does not have a return type and its name is same as the class name.

But, a constructor cannot be overridden. If you try to write a super class’s constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.

Example

class DemoTest{
   DemoTest(){
      System.out.println("This is the constructor of the demo class");
   }
}
public class OverridingConstructor extends DemoTest {
   DemoTest(){
      System.out.println("This is the constructor of the demo class");
   }
}

Output

C:\Sample>javac Example.java
Example.java:2: error: class Sample is public, should be declared in a file named Sample.java
public class Sample {
^
1 error

Sai Subramanyam
Sai Subramanyam

Passionate, Curious and Enthusiastic.

Updated on: 30-Jul-2019

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements