Java Inheritance
When one class extends another, the child class automatically gets access to the parent class members.
Example:
class A {
A() {
System.out.println("Constructor of A");
}
}
class B extends A {
B() {
System.out.println("Constructor of B");
}
}
public class Main {
public static void main(String[] args) {
B obj = new B();
}
}Output:
Constructor of A
Constructor of BWhy does the constructor of A run first?
Because Java automatically adds:
super();inside the constructor of B.
So this:
B() {
System.out.println("Constructor of B");
}is actually treated like:
B() {
super(); // calls constructor of parent class A
System.out.println("Constructor of B");
}super() is used to call the constructor of the superclass (parent class).
Using super() with Parameters
If the parent class has a parameterized constructor, you can pass values using super(value).
Example:
class A {
A(int x) {
System.out.println("Constructor of A: " + x);
}
}
class B extends A {
B() {
super(5); // calls A(int x)
System.out.println("Constructor of B");
}
}
public class Main {
public static void main(String[] args) {
B obj = new B();
}
}Output:
Constructor of A: 5
Constructor of BHere:
super(5);calls the constructor of class A that accepts an int.
this() Constructor Call
this() is used to call another constructor of the same class.
Example:
class A {
A() {
this(10); // calls parameterized constructor
System.out.println("Default constructor");
}
A(int x) {
System.out.println("Parameterized constructor: " + x);
}
}
public class Main {
public static void main(String[] args) {
A obj = new A();
}
}Output:
Parameterized constructor: 10
Default constructorHere:
this(10);calls the constructor of the same class that takes an int.
Difference Between super() and this()
KeywordPurposesuper()Calls constructor of parent classthis()Calls another constructor of same class
Important Rules
super()andthis()must be the first statement inside a constructor.
Correct:
A() {
super();
}Wrong:
A() {
System.out.println("Hello");
super(); // Error
}
You cannot use boththis()andsuper()in the same constructor directly because both must be first.
Wrong:
A() {
this();
super(); // Error
}Full Example Together
class A {
A() {
System.out.println("A default constructor");
}
A(int x) {
System.out.println("A parameterized constructor: " + x);
}
}
class B extends A {
B() {
this(20);
System.out.println("B default constructor");
}
B(int y) {
super(5);
System.out.println("B parameterized constructor: " + y);
}
}
public class Main {
public static void main(String[] args) {
B obj = new B();
}
}Output:
A parameterized constructor: 5
B parameterized constructor: 20
B default constructorFlow:
new B()callsB()B()callsthis(20)B(int y)callssuper(5)A(int x)executesControl returns to
B(int y)Control returns to
B()
More articles
Building a Lightweight Native Notes App in Go
