super Keyword in Java

The super keyword is a powerful tool in Java that is used to refer to the immediate parent class of a subclass. It is often used to access members of the parent class that have been overridden by the subclass, or to invoke a parent class’s constructor from a subclass.

One common use of the super keyword is to access variables or methods of the parent class that have been hidden by a subclass. For example, consider the following code:

class Animal {
  protected String name;
  protected void setName(String name) {
    this.name = name;
  }
}

class Dog extends Animal {
  private String name;
  public void setName(String name) {
    this.name = "Dog: " + name;
  }
  public void printName() {
    System.out.println(this.name);
  }
}

class Test {
  public static void main(String[] args) {
    Dog dog = new Dog();
    dog.setName("Fido");
    dog.printName();
  }
}

In this code, the Dog class has a name variable and a setName method that overrides the corresponding members of the Animal class. When the setName method is called on a Dog object, it sets the value of the Dog‘s name variable, rather than the Animal‘s name variable.

To access the Animal‘s name variable from the Dog class, we can use the super keyword. For example, we could modify the Dog class as follows:

class Dog extends Animal {
  private String name;
  public void setName(String name) {
    super.setName(name);
    this.name = "Dog: " + name;
  }
  public void printName() {
    System.out.println(super.name);
  }
}

Now, when the setName method is called on a Dog object, it first calls the setName method of the Animal class using the super keyword, setting the value of the Animal‘s name variable. It then sets the value of the Dog‘s name variable as before.

The super keyword can also be used to invoke a parent class’s constructor from a subclass. This is often done when creating a subclass that extends a parent class and adds additional functionality. For example:

class Animal {
  protected String name;
  public Animal(String name) {
    this.name = name;
  }
}

class Dog extends Animal {
  private int age;
  public Dog(String name, int age) {
    super(name);
    this.age = age;
  }
}

In this code, the Dog class has a constructor that takes a name and an age as arguments. It uses the super keyword to invoke the Animal class’s constructor, passing the name argument to it. This sets the value of the Animal‘s name variable, and the Dog‘s constructor then sets the value of its own age variable.

In summary, the super keyword is a useful tool in Java for accessing members of a parent class that have been overridden or hidden by a subclass, as well as for invoking a parent class’s constructor from a subclass. It is an important concept to understand when working with inheritance in Java, and is a powerful tool for building flexible and reusable code.

Leave a Reply

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x