Constructor Override Example Java

Constructor Override Example Java

By rule in Java, a constructor cannot be overridden but a method can be overridden.

It looks as if constructor is overridden but not.

The members of a class are instance variables and methods but not constructors because

  1. a constructor cannot be overridden.
  2. a constructor cannot be called with an object but method can be called. To call a constructor, an object must be created.
  3. in case of methods, we say, the "subclass method can call super class method". But it cannot be said with constructors and inturn we should say "subclass constructor can access super class constructor"; here, correct word is "access" and not "call". It is for the reason, a constructor cannot be overridden.
  4. we cannot call a super class constructor with super keyword. For constructors, specially one more term is created by
    Designers – super().
  5. in method overriding, the super class method and subclass method should be of the same – same name, same return type and same parameter list. In constructors, same name constructor cannot be written in another class; it is compilation error.

The last point in the above list is given as an example, but compiler raises error.

Constructor Override Example (observe error message)

Constructor Override
Output screenshot on Constructor Override

Observe the screenshot. Compiler thinks Test() as a method in Demo class (as constructor cannot be overridden) and warns there should be return type.

Practice and understand well this tutorial "Constructor Override Example".

One thought on “Constructor Override Example Java

Leave a Reply

Your email address will not be published. Required fields are marked *