Table of Contents
Inheritance and Constructors in Java
Inheritance brings with it several nuances that Java meticulously follows. Constructors also have a big role to play in this. As inheritance allows subclasses to use variables and fields of their superclass, the fields and variables must have to be initialized in the subclass. However, since the entities are not present in the subclass, its own constructor cannot initialize them. Therefore, the constructor of the superclass is automatically called when the derived class constructor is called. This feature is only allowed with constructors having no argument list.
Sample Code
class Base { Base () { System.out.println ( “Base Class Constructor called” ); } } class Derived extends Base { Derived () { System.out.println ( “Derived Class Constructor called” ); } } public class Main { public static void main (String args []) { Derived d = new Derived (); } }
OUTPUT
Base Class Constructor called
Derived Class Constructor called
Parameterized Constructors
The above method shows that unparameterized constructors are automatically invoked. However, when you want to call the parameterized constructor of a superclass inside a subclass, you can do so using the super() command. It is a mandate that the constructor call of the superclass must be the very first line of the subclass constructor.
Sample Code
class Base { int x; Base (int _x) { x = _x; } } class Derived extends Base { int y; Derived (int _x, int _y) { super (_x); y = _y; } void Display () { System.out.println (“x = ” + x + “, y =” + y); } } public class Main { public static void main (String args []) { Derived d = new Derived (10, 20); d.Display(); } }
OUTPUT
x = 10, y = 20
0 Comments