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");
}
}

Try it yourself


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
}
}

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.