1.
To Access Parent Class Variables
• If a subclass has a variable with the same
name as in its parent class, then super can be
used to refer to the parent class variable
To Access Parent Class Variables
class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = "Dog";
void display() {
[Link]("Child class name: " + name);
[Link]("Parent class name: " + [Link]);
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
2. To Call Parent Class Methods
• If the child class overrides a method of the
parent class, the super keyword can be used
to call the parent class version of that method
2. To Call Parent Class Methods
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
void show() {
[Link](); // Call parent class method
sound(); // Call child class method
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
3. To Call Parent Class Constructor
• The super() keyword is used to call the
constructor of the parent [Link] is
especially useful when the parent class has a
parameterized constructor
3. To Call Parent Class Constructor
class Animal {
Animal(String type) {
[Link]("Animal type: " + type);
}
}
class Dog extends Animal {
Dog(String name) {
super("Mammal"); // Call parent constructor
[Link]("Dog name: " + name);
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog("Buddy");
}
}
Complete Example
class Vehicle {
String brand;
int year;
Vehicle(String brand, int year) {
[Link] = brand;
[Link] = year;
[Link]("Vehicle Constructor: " + brand + " (" + year + ")");
}
}
class Car extends Vehicle {
int doors;
Car(String brand, int year, int doors) {
super(brand, year); // Call Vehicle constructor
[Link] = doors;
[Link]("Car Constructor: " + doors + " doors");
}
}
Cont..
class ElectricCar extends Car {
int batteryCapacity;
ElectricCar(String brand, int year, int doors, int batteryCapacity) {
super(brand, year, doors); // Call Car constructor
[Link] = batteryCapacity;
[Link]("ElectricCar Constructor: " + batteryCapacity + " kWh battery");
}
}
public class Main {
public static void main(String[] args) {
ElectricCar tesla = new ElectricCar("Tesla", 2024, 4, 100);
}
}