Java Inheritance Polymorphism
Java Inheritance Polymorphism
Polymorphism
1. Method Overriding in Java
AIM
To implement method overriding in Java.
PROGRAM
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class MethodOverride {
public static void main(String[] args) {
Dog d = new Dog();
d.sound();
}
}
OUTPUT
Dog barks
CONCLUSION
The program successfully overrides the method of the base class in the derived class.
AIM
To call the base class constructor using super keyword in Java.
PROGRAM
class Parent {
Parent() {
System.out.println("Parent class constructor called");
}
}
class Child extends Parent {
Child() {
super(); // Call to parent constructor
System.out.println("Child class constructor called");
}
}
public class SuperConstructor {
public static void main(String[] args) {
Child obj = new Child();
}
}
OUTPUT
Parent class constructor called
Child class constructor called
CONCLUSION
The program demonstrates how to use super() to call the base class constructor from a
subclass.
AIM
To call a base class method using the super keyword in Java.
PROGRAM
class Parent {
void display() {
System.out.println("Parent class display method");
}
}
class Child extends Parent {
void display() {
super.display(); // Call to parent method
System.out.println("Child class display method");
}
}
public class SuperMethod {
public static void main(String[] args) {
Child obj = new Child();
obj.display();
}
}
OUTPUT
Parent class display method
Child class display method
CONCLUSION
The program shows how to use super to invoke a method of the base class from the derived
class.
AIM
To implement run-time polymorphism using method overriding and dynamic dispatch in
Java.
PROGRAM
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void sound() {
System.out.println("Cat meows");
}
}
public class PolymorphismDemo {
public static void main(String[] args) {
Animal a;
a = new Dog();
a.sound(); // Dog's sound method is called
a = new Cat();
a.sound(); // Cat's sound method is called
}
}
OUTPUT
Dog barks
Cat meows
CONCLUSION
The program successfully demonstrates run-time polymorphism using dynamic method
dispatch.