Super keyword
Super Keyword: The Super keyword is a special keyword in Java that allows a subclass to inherit the attributes and behaviors of a superclass. This means tha...
Super Keyword: The Super keyword is a special keyword in Java that allows a subclass to inherit the attributes and behaviors of a superclass. This means tha...
Super Keyword:
The Super keyword is a special keyword in Java that allows a subclass to inherit the attributes and behaviors of a superclass. This means that a subclass can access and use the methods, variables, and constructors defined in the superclass.
Inheritance Hierarchy:
Subclass inherits from the superclass.
The superclass is an instance of a class that contains the implementation of the behavior.
The subclass inherits the behavior from the superclass.
Inheritance Example:
java
public class Animal {
private String name;
private int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Dog extends Animal {
public Dog(String name, int age) {
super(name, age);
}
@Override
public String getName() {
return "Dog";
}
}
Explanation:
The Animal class defines the name and age attributes and the getName and setName methods.
The Dog class extends the Animal class and implements the getName method, returning the string "Dog".
When we create an instance of Dog, we pass the name and age parameters to the super constructor.
This allows the Dog object to access and use the behavior implemented in the Animal class.
Benefits of Inheritance:
Code reuse: Subclasses can reuse existing code from the superclass.
Behavior inheritance: Subclasses can inherit behaviors from the superclass.
Flexibility: Subclasses can specialize the behavior of the superclass