Advertisement
Google Ad Slot: content-top
Java super() and this()
In Java, both super() and this() are used to refer to constructors, but they have distinct purposes and rules. Let’s explore each in detail:
super():
- Purpose: Refers to the constructor of the parent (superclass).
- Usage:
- To call the constructor of the parent class.
- It is used when a subclass needs to initialize the fields of the parent class.
Example
class Animal {
String name;
// Parent class constructor
Animal(String name) {
this.name = name;
System.out.println("Animal constructor called. Name: " + name);
}
}
class Dog extends Animal {
// Subclass constructor
Dog(String name) {
super(name); // Calls the parent class constructor
System.out.println("Dog constructor called.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy");
}
}
this():
- Purpose: Refers to the constructor of the current class.
- Usage:
- To call another constructor from the same class.
- Helps in constructor chaining within the same class.
Example
class Person {
String name;
int age;
// Constructor 1: Default constructor
Person() {
this("Unknown", 0); // Calls Constructor 2
System.out.println("Default constructor called.");
}
// Constructor 2: Parameterized constructor
Person(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Parameterized constructor called. Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person(); // Calls the default constructor
}
}