Can a constructor be overridden in java?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 29-Dec-2017 09:10:32
Advertisements