UNIT II – Polymorphism and Inheritance:
Polymorphism: Method overloading and overriding – Dynamic method dispatch; Inheritance: Definition – Super and sub
class, Types of inheritance: Single – Multilevel – Multiple – Hierarchical – Hybrid; Sub class constructors; Abstract
classes – Interfaces – Defining and Implementing Interface – Collections – Object cloning.
POLYMORPHISM
Polymorphism “Poly” means many “morph” means form. It is one of the feature in oops
that performs single action in different ways. For example class vehicle has method cars(). In that
cars are of different types XUV, ZEDON, HATCHBACK etc
Two types of polymorphism are there. They are as follows
Compile time polymorphism (Static Binding)
Run time polymorphism (Dynamic Binding)
Another one good example is that a person at the same time can have different characteristics. A
man act as a father, son, husband and an employee.
Program
Output
Method Overloading
Method overloading means defining multiple methods with the same name but different parameter lists in the same
class.
It is an example of compile-time polymorphism (static polymorphism).
Example
class Calculator {
// Method with 2 int parameters
int add(int a, int b) {
return a + b;
}
// Method with 3 int parameters
int add(int a, int b, int c) {
return a + b + c;
}
// Method with 2 double parameters
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator c = new Calculator();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
[Link]([Link](10.5, 20.5));
}
}
Output
30
60
31.0
Method Overriding
Method Overriding in Java is a feature of runtime polymorphism where a subclass provides its own implementation of
a method that is already defined in its superclass.
Rules for Method Overriding
The method in the subclass must have the same name as the method in the superclass.
The parameter list must be identical.
The return type must be the same or a subtype (covariant return type).
The access modifier cannot be more restrictive than the overridden method.
final, static, and private methods cannot be overridden.
The @Override annotation is recommended because it helps the compiler detect mistakes.
Example
// Superclass
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
// Subclass
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
[Link](); // Calls Dog's sound() method
}
}
Output:
Dog barks
Why use Method Overriding?
To provide a specific implementation of a method in a subclass.
To achieve runtime polymorphism.
To make code more flexible and reusable.
Dynamic Method Dispatch
Definition
Dynamic Method Dispatch is a mechanism in Java where the method to be executed is determined at runtime, not at
compile time.
It is also called Runtime Polymorphism because the overridden method is selected based on the actual object type.
Syntax
Superclass reference = new Subclass();
[Link]();
Although the reference is of the superclass type, the method of the subclass object is executed.
Example Program
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows");
}
}
public class DynamicDispatchDemo {
public static void main(String[] args) {
Animal a;
a = new Dog();
[Link]();
a = new Cat();
[Link]();
}
}
Output
Dog barks
Cat meows
INHERITANCE
It is the process of deriving a class from the base class. For example, one person is
getting the behavior of his parent is an example of inheritance. If one object acquires the
properties of another object. Inheritance is the mechanism of deriving new class from old one,
old class is knows as superclass and new class is known as subclass. The subclass inherits all of
its instances variables and methods defined by the superclass and it also adds its own unique
elements. Thus, we can say that subclass is specialized version of superclass.
Benefits of Java’s Inheritance
1. Reusability of code
2. Code Sharing
3. Consistency in using an interface
Classes
Superclass(Base Class) Subclass(Child Class)
It is a class from which other classes can It is a class that inherits some or all
be derived. members from superclass.
This is important because it supports the concept of hierarchical classification. Types of
inheritance are as follows
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchal Inheritance
Hybrid Inheritance
1. Single Inheritance - one class extends one class only
Base class
Derived class
Child Class inherited from Base Class.
Note: “extends” keyword is used to inherit a sub class
from superclass.
2. Multilevel Inheritance – It is a ladder or hierarchy of single level inheritance. It means if
Class A is extended by Class B and then further Class C extends Class B then the whole
structure is termed as Multilevel Inheritance. Multiple classes are involved in inheritance, but
one class extends only one. The lowermost subclass can make use of all its super classes'
members.
3. Hierarchical Inheritance - one class is extended by many subclasses. It is one-to-many
relationship.
B C
Syntax of Inheritance
class subclass extends superclass
{
……..//(METHODS AND FIELDS)
}
Program
Output
MULTILEVEL INHERITANCE EXAMPLE JAVA PROGRAM
Output
MULTILEVEL WITH CONSTRUCTOR EXAMPLE JAVA PROGRAM
//multilevel inheritance with constructor
Output
INTERFACE
An interface in java is a blueprint of a class. It has static constants and
abstract methods only. The interface in java is a mechanism to achieve fully
abstraction. There can be only abstract methods in the java interface not
method body. It is used to achieve fully abstraction and multiple inheritance in
Java.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve fully abstraction.
o By interface, we can support the functionality of multiple inheritances.
o It can be used to achieve loose coupling.
INTERFACE
1. Definition
An interface in Java is a blueprint of a class. It is mainly used to achieve abstraction and multiple
inheritance.
An interface can contain:
Abstract methods
Default methods
Static methods
Private methods
Constants
An interface is declared using the interface keyword.
A class implements an interface using the implements keyword.
Basic Syntax
interface InterfaceName {
void method1();
void method2();
}
class ClassName implements InterfaceName {
public void method1() {
// implementation
}
public void method2() {
// implementation
}
}
2. Example of Interface
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
[Link]("Dog barks");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
Output
Dog barks
Explanation
Animal is an interface.
sound() is an abstract method.
Dog implements the Animal interface.
Therefore, Dog must provide the implementation of sound().
Interface methods implemented in a class must be declared public.
3. Important Features of Interface
1. An interface is declared using the interface keyword.
2. A class implements an interface using implements.
3. An interface is mainly used to achieve abstraction.
4. A class can implement multiple interfaces.
5. Interface methods are traditionally public abstract by default.
6. Interface variables are public static final by default.
7. An interface cannot normally be instantiated directly.
8. Interfaces help Java achieve multiple inheritance of type.
9. Modern Java interfaces can also contain default, static, and private methods.
4. Interface Variables
Variables declared inside an interface are automatically:
public static final
Example:
interface Vehicle {
int SPEED = 100;
}
The above is equivalent to:
interface Vehicle {
public static final int SPEED = 100;
}
Therefore, the value cannot be modified.
[Link] = 200; // Error
5. Multiple Inheritance Using Interfaces
Definition
Multiple inheritance means that one class obtains features from more than one parent.
Java does not support multiple inheritance using classes.
Not allowed
class A {
}
class B {
}
class C extends A, B {
}
This produces a compilation error.
Why?
Java avoids multiple inheritance through classes mainly because of the ambiguity/diamond
problem.
Instead, Java provides multiple inheritance through interfaces.
6. Example: Multiple Inheritance Using Interfaces
interface Father {
void fatherProperty();
}
interface Mother {
void motherProperty();
}
class Child implements Father, Mother {
public void fatherProperty() {
[Link]("Father's Property");
}
public void motherProperty() {
[Link]("Mother's Property");
}
}
public class MultipleInterfaceDemo {
public static void main(String[] args) {
Child c = new Child();
[Link]();
[Link]();
}
}
Output
Father's Property
Mother's Property
Explanation
class Child implements Father, Mother
means that Child implements two interfaces.
Therefore, Child must implement all the abstract methods declared in both interfaces.
7. Multiple Interfaces
A class can implement more than one interface.
Syntax
class Child implements Interface1, Interface2, Interface3 {
}
Example:
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() {
[Link]("Method A");
}
public void methodB() {
[Link]("Method B");
}
}
8. Hierarchical Inheritance Using Classes
In hierarchical inheritance, multiple child classes inherit from the same parent class.
Diagram
Animal
/ \
Dog Cat
Example
class Animal {
void eat() {
[Link]("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
[Link]("Dog is barking");
}
}
class Cat extends Animal {
void meow() {
[Link]("Cat is meowing");
}
}
public class HierarchicalInheritance {
public static void main(String[] args) {
Dog d = new Dog();
Cat c = new Cat();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
Output
Animal is eating
Dog is barking
Animal is eating
Cat is meowing
Explanation
Both Dog and Cat inherit the eat() method from Animal.
9. Hybrid Inheritance Using Interfaces
Definition
Hybrid inheritance is a combination of two or more types of inheritance.
Java does not directly support hybrid inheritance through classes when it requires multiple
inheritance.
However, it can be implemented using interfaces.
Structure
A
/ \
B C
\ /
D
Example
interface A {
void displayA();
}
interface B extends A {
}
interface C extends A {
}
class D implements B, C {
public void displayA() {
[Link]("Hybrid Inheritance");
}
}
public class HybridInheritance {
public static void main(String[] args) {
D obj = new D();
[Link]();
}
}
Output
Hybrid Inheritance
Explanation
B extends A.
C extends A.
D implements both B and C.
Thus, different inheritance relationships are combined.
Interfaces allow this structure without the ambiguity associated with multiple class
inheritance.
10. extends vs implements
extends implements
Used for class inheritance Used when a class implements an interface
Class extends another class Class implements an interface
Interface can extend another interface Class can implement one or more interfaces
Example: class B extends A Example: class C implements A
Example
class Dog extends Animal {
}
class Dog implements Animal {
}
The second form is valid when Animal is an interface.
Difference Between Class and Interface in Java
Class Interface
An interface is a blueprint that defines a
A class is a blueprint for creating objects.
contract/behavior.
Declared using class keyword. Declared using interface keyword.
An interface can have constants, abstract methods,
A class can have instance variables, static
default methods, static methods, and private
variables, methods, constructors, etc.
methods.
Variables can be private, protected, public,
Interface fields are public static final by default.
etc.
Abstract interface methods have no implementation;
Methods can have implementations.
default and static methods can have implementations.
A class can have a constructor. An interface cannot have a constructor.
A class can be instantiated using new. An interface cannot normally be instantiated directly.
A class can extend only one class. An interface can extend multiple interfaces.
An interface cannot implement another interface; it
A class can implement multiple interfaces.
extends interfaces.
Uses extends for class inheritance. Uses extends to inherit from another interface.
A class is implemented by another class An interface is implemented by a class using
using extends. implements.
Supports inheritance through classes. Helps achieve multiple inheritance of type.
Class Interface
Example: class Dog extends Animal Example: class Dog implements Animal
Abstract Class
1. Definition
An abstract class is a class that is declared using the abstract keyword.
It is used when we want to provide common functionality to multiple subclasses while leaving
some methods for subclasses to implement.
Syntax
abstract class ClassName {
// variables
// concrete method
void display() {
[Link]("Concrete method");
}
// abstract method
abstract void show();
}
2. Abstract Method
An abstract method is a method that has a declaration but does not have a body.
Syntax
abstract void show();
A subclass must provide the implementation of the abstract method unless the subclass is also
abstract.
3. Example of Abstract Class
abstract class Animal {
// Abstract method
abstract void sound();
// Concrete method
void eat() {
[Link]("Animal is eating");
}
}
class Dog extends Animal {
// Implementation of abstract method
void sound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
Output
Dog barks
Animal is eating
Explanation
Animal is an abstract class.
It contains:
abstract void sound();
which is an abstract method.
It also contains:
void eat() {
[Link]("Animal is eating");
}
which is a concrete method.
Dog extends Animal and provides the implementation of sound().
4. Abstract Class Cannot Be Instantiated
We cannot directly create an object of an abstract class.
abstract class Animal {
abstract void sound();
}
The following is invalid:
Animal a = new Animal(); // Error
However, we can create a reference of the abstract class type:
Animal a = new Dog();
This is valid because Dog is a concrete subclass of Animal.
5. Abstract Class with Constructor
An abstract class can have a constructor.
abstract class Animal {
Animal() {
[Link]("Animal constructor");
}
abstract void sound();
}
class Dog extends Animal {
Dog() {
[Link]("Dog constructor");
}
void sound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}
}
Output
Animal constructor
Dog constructor
Dog barks
The abstract class constructor is called when the subclass object is created.
6. Abstract Class Can Have Variables
An abstract class can contain:
Instance variables
Static variables
Final variables
Methods
Constructors
Example:
abstract class Employee {
int salary = 50000;
abstract void work();
void displaySalary() {
[Link](salary);
}
}
7. Abstract Class Can Have Both Abstract and Concrete Methods
This is an important feature.
abstract class Vehicle {
abstract void start();
void stop() {
[Link]("Vehicle stopped");
}
}
Here:
start() → abstract method
stop() → concrete method
8. Abstract Class and Inheritance
An abstract class is generally used as a base class.
Animal
(Abstract Class)
/ \
/ \
Dog Cat
Example:
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
}
class Cat extends Animal {
void sound() {
[Link]("Cat meows");
}
}
9. Important Rules of Abstract Class
1. An abstract class is declared using the abstract keyword.
2. An abstract class cannot be instantiated directly.
3. It can contain abstract methods.
4. It can also contain concrete methods.
5. It can have constructors.
6. It can have instance and static variables.
7. A subclass uses extends to inherit an abstract class.
8. A concrete subclass must implement all inherited abstract methods.
9. An abstract class can have zero or more abstract methods.
10. An abstract class can be used as a reference type.
10. Abstract Class vs Normal Class
Abstract Class Normal Class
Declared using abstract Declared using class
Abstract Class Normal Class
Cannot be instantiated directly Can be instantiated
Can contain abstract methods Cannot contain abstract methods
Can contain concrete methods Can contain concrete methods
Can have constructors Can have constructors
Can have variables Can have variables
Used as a base class Can be used as a normal class
Subclass generally provides missing implementations No such requirement
11. Abstract Class vs Interface
Abstract Class Interface
Declared using abstract class Declared using interface
A class implements an interface using
A class extends an abstract class using extends
implements
Can have constructors Cannot have constructors
Can have instance variables Fields are public static final by default
Can have abstract, default, static and private
Can have abstract and concrete methods
methods
A class can extend only one class A class can implement multiple interfaces
Can contain instance state Mainly represents a contract/capability
Suitable when classes share common state and
Suitable for defining a common contract
behavior
Example
abstract class Shape {
abstract void area();
void display() {
[Link]("This is a shape");
}
}
class Circle extends Shape {
void area() {
[Link]("Area of Circle");
}
}
public class Main {
public static void main(String[] args) {
Circle c = new Circle();
[Link]();
[Link]();
}
}
final Keyword in Java
The final keyword in Java is used to restrict modification. It can be applied to:
1. Variables
2. Methods
3. Classes
1. final Variable
A final variable cannot be reassigned after it has been initialized.
Example
class Student {
final int ROLL_NO = 101;
void display() {
[Link](ROLL_NO);
}
}
The following is not allowed:
ROLL_NO = 102; // Compilation Error
Output
101
Important Point
A final variable is commonly called a constant when it is declared as:
static final
Example:
class Test {
static final double PI = 3.14159;
}
Conventionally, constants are written in uppercase letters.
2. final Method
A final method cannot be overridden by a subclass.
Example
class Parent {
final void display() {
[Link]("Parent method");
}
}
class Child extends Parent {
// Error: cannot override final method
// void display() {
// [Link]("Child method");
// }
}
Why use a final method?
When the programmer wants to ensure that a method's implementation cannot be changed by
subclasses.
3. final Class
A final class cannot be inherited.
Example
final class Vehicle {
void display() {
[Link]("Vehicle");
}
}
We cannot extend it:
class Car extends Vehicle {
}
This produces a compilation error because Vehicle is final.
Real-world example
String is a famous example of a final class in Java:
public final class String
Therefore, we cannot create a subclass of String.
4. final Parameter
The final keyword can also be used with method parameters.
class Test {
void display(final int x) {
[Link](x);
}
}
Inside the method, x cannot be reassigned:
x = 20; // Error
final variable → Cannot be reassigned
final method → Cannot be overridden
final class → Cannot be inherited
final parameter → Cannot be reassigned inside the method
// Demonstration of final variable, final method and final class
class Parent {
// Final variable
final int NUMBER = 100;
// Final method
final void display() {
[Link]("This is a final method");
}
}
// Final class cannot be inherited
final class Child extends Parent {
void show() {
[Link]("Final variable value: " + NUMBER);
}
}
public class FinalDemo {
public static void main(String[] args) {
Child obj = new Child();
// Access final variable
[Link]("Number = " + [Link]);
// Access final method
[Link]();
// Access normal method
[Link]();
// [Link] = 200; // Error: final variable cannot be changed
}
}
Output
Number = 100
This is a final method
Final variable value: 100
Object Cloning in Java
What is Object Cloning?
Object Cloning is the process of creating an exact copy of an existing object.
Instead of creating a new object manually and copying each value, Java provides the clone() method
to create a duplicate object.
Definition
Object cloning is the process of creating a new object with the same state (data) and behavior as an
existing object.
Why Do We Need Object Cloning?
Suppose you have an object with many fields. Creating another object and copying each field
manually is time-consuming.
Object cloning creates a copy of an existing object.
The class must implement the Cloneable interface.
The clone() method belongs to the Object class.
By default, clone() performs a shallow copy.
Deep copy must be implemented manually when independent copies of referenced objects are
required.
If a class does not implement Cloneable, calling clone() results in a
CloneNotSupportedException.
Without cloning:
Student s2 = new Student();
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
With cloning:
Student s2 = (Student) [Link]();
Cloning makes copying objects easier and faster.
How Object Cloning Works
To clone an object in Java:
1. The class must implement the Cloneable interface.
2. Override the clone() method (or make it accessible).
3. Call the clone() method on the object.
Syntax
ClassName obj2 = (ClassName) [Link]();
Example Program
class Student implements Cloneable {
int id;
String name;
Student(int id, String name) {
[Link] = id;
[Link] = name;
}
public Object clone() throws CloneNotSupportedException {
return [Link]();
}
public static void main(String[] args) throws CloneNotSupportedException {
Student s1 = new Student(101, "Rahul");
Student s2 = (Student) [Link]();
[Link]([Link] + " " + [Link]);
[Link]([Link] + " " + [Link]);
}
}
Output
101 Rahul
101 Rahul
Here, s2 is a clone (copy) of s1.
Cloneable Interface
Cloneable is a marker interface in Java.
A marker interface does not contain any methods. It only tells the JVM that the object is allowed to
be cloned.
Example:
class Student implements Cloneable
{
}
If the class does not implement Cloneable, calling clone() throws a CloneNotSupportedException.
clone() Method
The clone() method is defined in the Object class.
Syntax
protected Object clone() throws CloneNotSupportedException
Purpose
Creates and returns a copy of the object.
By default, performs a shallow copy.
Advantages of Object Cloning
Easy to duplicate objects
Saves programming time
Improves performance compared to manual copying
Useful for creating backup copies of objects
Avoids repetitive field assignments
Collections
The Java Collections Framework (JCF) is a set of classes and interfaces that provides a standard
way to store, retrieve, and manipulate groups of objects. It offers ready-made data structures like lists,
sets, queues, and maps.
Why use Collections?
Store multiple objects dynamically (size can grow or shrink).
Perform operations like searching, sorting, inserting, and deleting efficiently.
Reduce coding effort using built-in classes and algorithms.
Collection Hierarchy
Main Interfaces
1. List
Stores elements in insertion order.
Allows duplicate elements.
Access elements using index.
Examples: ArrayList, LinkedList, Vector
import [Link].*;
public class Demo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Apple");
[Link](list);
}
}
Output:
[Apple, Banana, Apple]
2. Set
Does not allow duplicate elements.
No indexing.
Used when unique elements are required.
Examples: HashSet, LinkedHashSet, TreeSet
Set<Integer> set = new HashSet<>();
[Link](10);
[Link](20);
[Link](10);
[Link](set);
Output:
[10, 20]
3. Queue
Follows FIFO (First In, First Out).
Used for scheduling and task processing.
Examples: PriorityQueue, LinkedList
Queue<Integer> queue = new LinkedList<>();
[Link](10);
[Link](20);
[Link]([Link]()); // Removes and returns 10
4. Map
Stores data as key-value pairs.
Keys are unique; values can be duplicated.
Map is not a subtype of Collection.
Examples: HashMap, TreeMap, LinkedHashMap
Map<Integer, String> map = new HashMap<>();
[Link](1, "John");
[Link](2, "Alice");
[Link]([Link](1));
Output:
John
Common Collection Classes
Class Ordered Duplicates Null Allowed Best Use
ArrayList Yes Yes Yes Fast random access
LinkedList Yes Yes Yes Frequent insertion/deletion
Class Ordered Duplicates Null Allowed Best Use
HashSet No No One null Unique elements
LinkedHashSet Yes No One null Unique elements with insertion order
TreeSet Sorted No No Sorted unique elements
HashMap No Keys: No One null key Fast key-value lookup
LinkedHashMap Yes Keys: No One null key Maintain insertion order
TreeMap Sorted Keys: No No null keys Sorted key-value pairs
Common Methods
Method Description
add() Adds an element
remove() Removes an element
get() Gets element by index (List) or value by key (Map)
contains() Checks if an element exists
size() Returns number of elements
isEmpty() Checks if the collection is empty
clear() Removes all elements
Advantages of Collections
Dynamic size.
Built-in sorting and searching.
Reusable and efficient data structures.
Improves code readability and maintainability.