Example for Method Overriding:
class Animal {
public void makeSound() {
System.out.println("Animal is making a sound");
}
}
class Dog extends Animal {
public void makeSound() {
System.out.println("Dog is barking");
}
}
class Cat extends Animal {
public void makeSound() {
System.out.println("Cat is meowing");
}
}
class MethodOverridingExample {
public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();
Cat cat = new Cat();
animal.makeSound();
dog.makeSound();
cat.makeSound();
}
}
Example for ‘super’ keyword:
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void display() {
System.out.println("Value of x in Child class: " + x);
System.out.println("Value of x in Parent class: " + super.x);
}
}
class SuperKeywordExample {
public static void main(String[] args) {
Child child = new Child();
child.display();
}
}