Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Constructor Overriding Possible?

What i know is, the compiler writes a default no argument constructor in the byte code. But if we write it ourselves, that constructor is called automatically. Is this phenomena a constructor overriding?

like image 203
Gopal Avatar asked Feb 24 '11 03:02

Gopal


People also ask

Can constructor be overloaded vs overridden?

Neither. Constructors are different from methods. You overload a constructor by writing multiple constructors in the same class, not in inherited classes. And constructors aren't subject to overriding.

Is constructor overriding possible in python?

Python constructor overriding mean one method will overrides the other. The parent class and child class both have the constructor and the child will override the parent constructor. After writing the above code (python constructor overriding) the output will appear as a “ This is Son class constructor”.


2 Answers

Constructors are not normal methods and they cannot be "overridden". Saying that a constructor can be overridden would imply that a superclass constructor would be visible and could be called to create an instance of a subclass. This isn't true... a subclass doesn't have any constructors by default (except a no-arg constructor if the class it extends has one). It has to explicitly declare any other constructors, and those constructors belong to it and not to its superclass, even if they take the same parameters that the superclass constructors take.

The stuff you mention about default no arg constructors is just an aspect of how constructors work and has nothing to do with overriding.

like image 135
ColinD Avatar answered Oct 06 '22 00:10

ColinD


What you describe isn't overriding. If you don't specify a default constructor, the compiler will create a default constructor. If it's a subclass, it will call the default parent constructor(super()), it will also initialize all instance variables to a default value determined by the type's default value(0 for numeric types, false for booleans, or null for objects).

Overriding happens when a subclass has the same name, number/type of parameters, and the same return type as an instance method of the superclass. In this case, the subclass will override the superclass's method. Information on overriding here.

like image 22
Eddie Flores Avatar answered Oct 06 '22 00:10

Eddie Flores