EXPERIMENT – 7
INHERITANCE AND POLYMORPHISM
Name of the Experiment:
Inheritance and Polymorphism in Java
Date:
______________
Aim:
To demonstrate inheritance and polymorphism in Java by creating a superclass and
subclass, overriding methods, and using the super keyword to access parent class
constructor and methods.
Requirements
Software:
Java Development Kit (JDK), Any Java IDE
Hardware:
Computer System
Theory
Inheritance is an important concept of Object-Oriented Programming in which one class
acquires the properties and behaviors of another class. The class whose properties are
inherited is called the superclass, and the class that inherits them is called the subclass.
Polymorphism means one method having different forms. In Java, polymorphism is
achieved through method overriding, where a subclass provides its own implementation of
a method already defined in the superclass.
The super keyword is used to refer to the immediate parent class object. It can be used to
call parent class constructors and methods.
Algorithm
1. Create a superclass with a constructor and a method.
2. Create a subclass using the extends keyword.
3. Override the superclass method in the subclass.
4. Use the super keyword to call the parent class constructor and method.
5. Create the main class and execute the program.
Program
class Parent {
Parent() {
[Link]("Parent class constructor called");
}
void display() {
[Link]("This is the parent class method");
}
}
class Child extends Parent {
Child() {
super();
[Link]("Child class constructor called");
}
@Override
void display() {
[Link]();
[Link]("This is the child class method");
}
}
public class InheritancePolymorphism {
public static void main(String[] args) {
Child obj = new Child();
[Link]();
}
}
Output
Parent class constructor called
Child class constructor called
This is the parent class method
This is the child class method
Result
Thus, basic inheritance, method overriding, and the use of the super keyword were
successfully implemented in Java.
Viva Voce Questions
1. What is inheritance?
2. What is polymorphism?
3. What is method overriding?
4. What is the use of the super keyword?
5. Can constructors be overridden?
Faculty Signature:
______________