|
| 1 | +# Constructors in Inheritance in Java |
| 2 | +### Constructors in Inheritance: |
| 3 | +- When a drived class is extended from the base class, the constructor of the base class is executed first followed by the constructor of the derived class. For the following Inheritance hierarchy , the constructors are executed in the order: |
| 4 | + |
| 5 | +1. C1- Parent |
| 6 | +2. C2 - Child |
| 7 | +3. C3 - Grandchild |
| 8 | + |
| 9 | +### Constructors during constructor overloading : |
| 10 | +- When there are multiple constructors in the parent class, the constructor without any parameters is called from the child class. |
| 11 | +- If we want to call the constructor with parameters from the parent class, we can use the super keyword. |
| 12 | +- super(a, b) calls the constructor from the parent class which takes 2 variables |
| 13 | + |
| 14 | +``` |
| 15 | +class Base1{ |
| 16 | + Base1(){ |
| 17 | + System.out.println("I am a constructor"); |
| 18 | + } |
| 19 | + Base1(int x){ |
| 20 | + System.out.println("I am an overloaded constructor with value of x as: " + x); |
| 21 | + } |
| 22 | +} |
| 23 | +
|
| 24 | +class Derived1 extends Base1{ |
| 25 | + Derived1(){ |
| 26 | + //super(0); |
| 27 | + System.out.println("I am a derived class constructor"); |
| 28 | + } |
| 29 | + Derived1(int x, int y){ |
| 30 | + super(x); |
| 31 | + System.out.println("I am an overloaded constructor of Derived with value of y as: " + y); |
| 32 | + } |
| 33 | +} |
| 34 | +
|
| 35 | +class ChildOfDerived extends Derived1{ |
| 36 | + ChildOfDerived(){ |
| 37 | + System.out.println("I am a child of derived constructor"); |
| 38 | + } |
| 39 | + ChildOfDerived(int x, int y, int z){ |
| 40 | + super(x, y); |
| 41 | + System.out.println("I am an overloaded constructor of Derived with value of z as: " + z); |
| 42 | + } |
| 43 | +} |
| 44 | +public class cwh_46_constructors_in_inheritance { |
| 45 | + public static void main(String[] args) { |
| 46 | + // Base1 b = new Base1(); |
| 47 | + // Derived1 d = new Derived1(); |
| 48 | + // Derived1 d = new Derived1(14, 9); |
| 49 | + // ChildOfDerived cd = new ChildOfDerived(); |
| 50 | + ChildOfDerived cd = new ChildOfDerived(12, 13, 15); |
| 51 | + } |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +**Handwritten Notes: [Click to Download](https://api.codewithharry.com/media/videoSeriesFiles/courseFiles/java-tutorials-for-beginners-46/JavaChapter10.pdf)** |
| 56 | + |
| 57 | +**Ultimate Java Cheatsheet: [Click To Download](https://api.codewithharry.com/media/videoSeriesFiles/courseFiles/java-tutorials-for-beginners-46/UltimateJavaCheatSheet.pdf)** |
0 commit comments