Inheritance and Polymorphism
Inheritance and Polymorphism
Introduction
•The capability of a class to derive properties and characteristics
from another class is called Inheritance.
•Promotes ‘code reusability’.
•Superclass (Parent class): The class from which properties and
methods are inherited.
•Subclass (Child class): The class that inherits the properties and
methods from the superclass.
•A subclass inherits all members of its superclass, but it cannot
access members that are declared as private in the superclass.
•Syntax:
class DerivedClass extends BaseClass
{
//methods and fields
}
class A {
Exam Protected int number;
ple public void display()
{
[Link]("This is the display method of the superclass.");
}
}
class B extends A
{ String message;
public void show() {
[Link]("This is the show method of the subclass.");
}
}
public class Main {
public static void main(String[] args)
{ B obj = new B();
[Link](); // Inherited from superclass [Link](); // Defined in
subclass
} }
Access modifier for inheritance
1. private:
•The member is accessible only within the same class.
•It cannot be accessed by subclasses, even through inheritance.
2. default (package-private):
•If no modifier is specified, it is accessible only within the same package.
•It cannot be accessed by subclasses in a different package, even if inherited.
3. protected:
•The member is accessible within the same package (like default).
•It is also accessible by subclasses, even if they are in different packages.
•However, subclasses in different packages can access the protected members only through inheritance,
not directly via an object reference.
4. public:
•The member is accessible everywhere—within the same class, package, subclass, or any other class.
class Animal {
private String type = "Mammal"; // private: Not accessible to subclass
String habitat = "Land"; // default: Accessible only within the same package
protected String name = "Animal"; // protected: Accessible within subclass (even in different packages)
public int age = 5; // public: Accessible everywhere
private void privateMethod()
{ [Link]("Private method in
Animal");
}
protected void protectedMethod() {
[Link]("Protected method in Animal");
}
}
class Dog extends Animal { // Subclass in the same package
public void showInfo() {
// [Link](type); // ERROR: private member not accessible
[Link](habitat); // Accessible: default member (same
package) [Link](name); // Accessible: protected
member [Link](age); // Accessible: public member
// privateMethod(); // ERROR: private method not accessible
protectedMethod(); // Accessible: protected method
}
}
Protected members are accessible in subclasses in
different packages
// File: [Link] // File: [Link]
// Package: packageA // Package: packageB
package packageA; package packageB;
public class Animal { import [Link];
protected String name; public class Dog extends Animal
public Animal(String name) { { public Dog(String name) {
[Link] = name; [Link] = name; // Accessing protected member directly
} }
protected void display() public void showDetails() {
{ [Link]("Animal name: " + [Link]("Dog name: " + name); // Accessing
name); protected member directly
} display(); // Calling protected method
} }
// File: [Link] }
// Package: packageB
package packageB;
public class Main {
public static void main(String[] args)
{ Dog dog = new Dog("Buddy");
[Link](); // Access protected members
} }
Types of Inheritance
•Single Inheritance
•Multilevel Inheritance
•Hierarchical Inheritance
•Multiple Inheritance
Single Inheritance
• When a class extends only one parent class.
• Example: class B extends
A class Animal{
void eat(){[Link]("eating...");} A
}
class Dog extends Animal{
B
void bark(){[Link]("barking...");}
}
class TestInheritance{
public static void main(String args[])
{ Dog d=new Dog();
[Link]();
[Link]();
}}
Multilevel Inheritance
•When there is a chain of inheritance, it is known as multilevel inheritance.
class Animal{
void eat(){[Link]("eating...");}
}
A
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
B
class BabyDog extends Dog{
void weep(){[Link]("weeping...");}
}
class TestInheritance2{ C
class Animal
{ public Animal()
{
[Link]("Animal constructor called.");
}
}
class Mammal extends Animal
{ public Mammal() { O/P:
[Link]("Mammal constructor called."); Animal constructor called.
} Mammal constructor called.
} Dog constructor called.
class Dog extends Mammal
{ public Dog() {
[Link]("Dog constructor called.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog(); // Creating an object of Dog
}
}
Hierarchical Inheritance
• When two or more classes inherits a single class.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{ A
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");} B C
}
class TestInheritance3{
public static void main(String args[])
{ Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//Error
}}
Multiple Inheritance
•A class can inherit from more than one superclass.
•Java doesn’t support multiple inheritance with classes. B A
Person(int i) {
[Link]("Person class Constructor");
}
}
class Student extends Person
{ Student() {
// invoke or call parent class constructor
super(10);
[Link]("Student class Constructor");
}
}
class Test {
public static void main(String[] args)
{
Student s = new Student();
Use of super to access superclass
constructors
class Vehicle { public void displayCarInfo()
protected String model; // Protected member { [Link]("Car Color: " + color);
protected int year; displayInfo(); // Call superclass method to display model
public Vehicle(String model, int year) and year
{ [Link] = model; }
[Link] = year; }
}
public void displayInfo() { public class SuperExample {
[Link]("Model: " + model + ", Year: " + year); public static void main(String[] args) {
} Car car = new Car("Toyota", 2022, "Red"); // Create a Car
} object
class Car extends Vehicle { [Link](); // Call method to display car
private String color; // Subclass member information
public Car(String model, int year, String color) { }
// Call the superclass constructor to initialize model and year }
super(model, year);
[Link] = color; // Initialize color
}
// Method to display car information
Order of execution
• When you use super() in the subclass constructor, it explicitly calls the constructor of the superclass. If super() is not explicitly called, Java
automatically calls the no-argument constructor of the superclass (if available).
class Animal {
public Animal(String name) {
[Link]("Animal constructor called. Name: " + name);
}
}
class Mammal extends Animal
{ public Mammal(String name) {
super(name); // Explicitly calling Animal constructor
[Link]("Mammal constructor called.");
} O/P
}
Animal constructor called. Name: Buddy
class Dog extends Mammal
{ public Dog(String name) {
Mammal constructor called.
super(name); // Explicitly calling Mammal constructor Dog constructor called.
[Link]("Dog constructor called.");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog("Buddy"); // Creating an object of Dog
}
}
Real-life Example class Bike extends Vehicle { // Subclass: Bike
class Vehicle { // Superclass: private boolean hasCarrier;
Vehicle protected String brand;
public Bike(String brand, int speed, boolean hasCarrier)
protected int speed; { super(brand, speed); // Call the constructor of the
public Vehicle(String brand, int speed) { superclass
[Link] = hasCarrier;
[Link] = brand; }
[Link] = speed; public void displayBikeDetails() {
} displayInfo(); // Reuse the superclass method
[Link]("Has carrier: " + (hasCarrier ? "Yes" :
public void displayInfo() { "No"));
[Link]("Brand: " + brand + " | Speed: " + }
speed + " km/h"); }
}
} public class Main {
class Car extends Vehicle { // Subclass: public static void main(String[] args) {
Car private int numDoors;
public Car(String brand, int speed, int numDoors) { Car car = new Car("Toyota", 180, 4);
super(brand, speed); // Call the constructor of the [Link]();
superclass [Link]();
[Link] = numDoors; Bike bike = new Bike("Yamaha", 120, true);
[Link]();
}
}
public void displayCarDetails() {
}
displayInfo(); // Reuse the superclass method
[Link]("Number of doors: " + numDoors);
}
}
Final keyword
•Final keyword is a modifier that can be applied to variables,
methods, and classes to indicate that they cannot be changed or
overridden.
•When a variable is declared as final, it means that its value cannot
be changed once it has been assigned.
• final int x = 10;
• x = 20; // This will cause a compilation error
•When a method is declared as final, it cannot be overridden
by subclasses.
•When a class is declared as final, no other class can extend it.
Final Methods
class Parent {
public final void display()
{ [Link]("This is a final method.");
}
}
class Child extends Parent {
// This will cause a compilation error
// public void display() {
// [Link]("Trying to override final method.");
// }
}
public class FinalMethodExample
{ public static void main(String[] args)
{
Child child = new Child();
[Link](); // Calls the final method from the Parent class
}
}
Final Classes
final class FinalClass {
public void show() {
[Link]("This is a final class.");
}
}
// This will cause a compilation error
// class SubClass extends FinalClass {
// }
public class FinalClassExample {
public static void main(String[] args)
{ FinalClass obj = new FinalClass();
[Link]();
}
}
Polymorphism
•The word ‘polymorphism’ means ‘having many forms’.
•In Java, it refers to the ability of an object to take on multiple forms.
•Types:
• Compile time Polymorphism
• Run time Polymorphism
Compile time polymorphism
•It is also known as static polymorphism.
•This type of polymorphism is achieved by function overloading
or operator overloading.
•Java does not support operator overloading.
•The method call is bound with method body at compile-time.
Run time polymorphism
•It is also known as Dynamic Method Dispatch.
•This type of polymorphism is achieved by Method Overriding.
•Method call is resolved at run time.
•Supports late binding.
•In runtime polymorphism, a subclass provides a specific
implementation of a method that is already defined in its
superclass.
• The method to be executed is determined at runtime, depending
on the object type, even if the reference is of the superclass type.
Method Overriding
• Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes
or parent classes.
• Used for run time polymorphism.
• Conditions:
• The method in the subclass must have the same name, return type (or a covariant return
type), and parameter list as the method in the superclass.
• if there is a relationship through inheritance between the subclass and the superclass.
• Access Level: The access level of the overriding method cannot be more restrictive than
the overridden method in the superclass. For example, if the superclass method is public,
the subclass method must also be public or less restrictive.
Method Overriding Example:
class Animal {
•It is recommended (though not void sound() {
mandatory) to use the @Override [Link]("Animal makes a sound");
}
annotation when overriding a method. }
This helps the compiler identify
mistakes, like incorrect method class Dog extends Animal {
@Override
signatures. void sound() { //[Link]();
[Link]("Dog barks");
•Static, Final, and Private Methods: }
These methods cannot be overridden }
because static methods are bound at public class Main {
compile-time, and final and private public static void main(String[] args) {
methods are not inherited by Dog myDog = new Dog();
[Link]();
subclasses. }
}
A real-world example
Banking example
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class A{
int x = 10;
}
class B extends
A{ int x = 20;
}
public class Test{
public static void main(String args[])
{ A a = new B(); // object of type B
[Link](a.x); //OP:10
}
}
Abstract class
•An abstract class in Java is a class that cannot be instantiated on
its own and serves as a blueprint for other classes.
•It may contain abstract methods (methods without a body) as well
as non-abstract methods (methods with a body).
•Abstract classes can have constructors, but these are called when
a subclass is instantiated.
•Illustration of Abstract class:
abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}
Important observations about abstract
classes
• An instance of an abstract class can not be created.
• We can have an abstract class without any abstract method.
• There can be a final method in abstract class but any abstract method
in class(abstract class) can not be declared as final.
• We can define static methods in an abstract class.
• If a class contains at least one abstract method then compulsory should declare
a class as abstract.
• If the Child class is unable to provide implementation to all abstract methods of
the Parent class then we should declare that Child class as abstract so that the next
level Child class should provide implementation to the remaining abstract method.
• Elements abstract class can have
• data member
• abstract method
• method body (non-abstract method)
• constructor
• main() method.
Example
abstract class Sunstar
{ abstract void
printInfo();
}
// Abstraction performed using extends
class Employee extends Sunstar
{ void printInfo() {
String name = "avinash";
int age = 21;
float salary = 222.2F;
[Link](name);
[Link](age);
[Link](salary);
}
}
class Base {
public static void main(String args[])
{ Sunstar s = new Employee();
[Link]();
}
}
Example: Abstract Class having constructor, data member, and
methods
import [Link].*;
abstract class Subject [Link]();
{ Subject() { [Link]();
[Link]("Learning Subject"); }
} }
abstract void syllabus();
void Learn(){
[Link]("Preparing Right Now!");
} O/P:
} Learning Subject
class IT extends Subject C , Java , C++
{ void syllabus(){ Preparing Right
[Link]("C , Java , C++"); Now!
}
}
class Test {
public static void main(String[] args) {
Subject x=new IT();
Example: Abstract class without any abstract
method
abstract class Base {
// Demo method. This is not an abstract method.
void fun()
{
// Print message if class 1 function is called
[Link]("Function of Base class is called");
}
}
class Derived extends Base {
}
class Main {
public static void main(String args[])
{
Derived d = new Derived();
[Link]();
}
}
Example
import [Link].*; // FirstChild then it will throw compile time error as did't
abstract class Demo override all the abstract methods
{
abstract void // FirstChild f=new FirstChild();
m1(); abstract // f.m1();
void m2();
abstract void SecondChild s = new SecondChild();
m3(); s.m1();
} s.m2();
abstract class FirstChild extends Demo { s.m3();
public void m1() }
{ [Link]("Inside m1"); }
}
}
class SecondChild extends FirstChild
{ public void m2()
{ [Link]("Inside m2");
}
public void m3() {
[Link]("Inside m3");
}
}
class Test {
public static void main(String[] args) {
// if we remove the abstract keyword from FirstChild Class and
uncommented below obj creation for
Practical use cases
•A use case for an abstract class in Java is in a vehicle rental system. The
abstract class Vehicle could define common attributes like vehicleID,
rentalCost, and methods like startRental() and endRental(), while leaving
an abstract method calculateRentalCost() for subclasses like Car, Bike,
and Truck to implement based on their own rental cost calculations (e.g.,
hourly, daily, or based on mileage). This ensures all vehicles follow the
same rental flow but handle cost calculations specific to their type.
•In a travel booking system, an abstract class Booking could define
common methods like confirmBooking() and cancelBooking(), while
leaving an abstract method calculatePrice() to be implemented by
subclasses such as FlightBooking, HotelBooking, and CarRentalBooking.
Each type of booking would have its own way of calculating the price, but
the process of confirming and canceling the booking would remain
consistent across all types.
Interface
• The interface in Java is a mechanism to achieve abstraction.
• An abstract type used to specify the behavior of a class.
• A Java interface contains static constants and abstract methods.
• Constants: Interfaces can have variables, but they are implicitly public, static,
and final.
• An interface cannot contain a constructor (as it cannot be used to create objects)
• A class that implements an interface must provide the concrete
implementation for all methods declared in the interface.
• Multiple inheritance: A class can implement multiple interfaces, enabling a
form of multiple inheritance, which is not possible with classes. // A simple
interface
interface Player
{
final int id = 10;
int move();
}
Relationship Between Class and Interface
• A class can extend another class, and similarly, an interface can extend another
interface. However, only a class can implement an interface, and the reverse
(an interface implementing a class) is not allowed.
• Difference Between Class and Interface
Class Interface
In an interface, you must initialize variables as they
In class, you can instantiate variables and create an
are final but you can’t create an
object.
object.
A class can contain concrete (with The interface cannot contain concrete (with
implementation) methods implementation) methods.
state [Link]();
} [Link]();
}
Static and default methods in interfaces
• From JDK 8, we can now define static and default methods in interfaces.
• Default method: To allow developers to add new functionality to interfaces without forcing all
implementing classes to change. Existing classes still compile fine — they automatically “inherit” the default
method.
• Static methods in interfaces are utility or helper methods related to the interface. They belong to the
interface itself, not to any implementing class.
• Note: Static methods of interfaces are not inherited by implementing classes.
interface }
In1{ final int a }
= 10;
static void display(){
[Link](“static method");
}
}
class TestClass implements
In1{ public static void main (String[]
args){
[Link]();
int = 10;
e default void display(){
r [Link](“default method");
f }
a }
c class TestClass implements
e In1{ public static void main (String[]
args){
I
TestClass t = new TestClass();
n
[Link]();
1
}
{
}
f
i
n
a
l
i
n
t
a
Extending Interfaces
• One interface can inherit another by the use }
of keyword extends. public void method2()
• When a class implements an interface that inherits { [Link]("Method
another interface, it must provide an 2");
implementation for all methods required by the }
interface inheritance chain. public void method3()
{ [Link]("Method
3");
//Example: }
interface A { }
void
method1();
void method2();
}
interface B extends A {
void method3();
}
class Test implements B {
public void method1(){
[Link]("Method 1");
Multiple Inheritance in Java Using
Interface
interface API { [Link]("Display from Interface1");
// Default method }
default void show() public void print()
{ {
[Link]("Default API"); [Link]("Print from Interface2");
} }
} public static void main(String args[])
{
interface Interface1 extends API { TestClass d = new TestClass();
// Abstract method
void display(); [Link](); // Default method from API
} [Link](); // Overridden method from Interface1
[Link](); // Overridden method from Interface2
interface Interface2 extends API { }
// Abstract method }
void print();
}
// InterfaceD extends InterfaceA and InterfaceB // Main class to test the implementation
interface InterfaceD extends InterfaceA, InterfaceB { public class Main {
void methodD(); public static void main(String[] args)
} { ImplementingClass obj = new ImplementingClass();
[Link]();
// Class implementing InterfaceC and providing [Link]();
implementations [Link]();
class ImplementingClass implements InterfaceC { }
@Override }
public void methodA() {
MCQ
class Parent { abstract class Animal {
void show() { public int age;
[Link]("Parent Show");
S }
special(); Animal() {
age = 5;
void special() { }
[Link]("Parent Special"); abstract public void makeSound();
} abstract final public void displayAge();
} }
class Child extends Parent { class Dog extends Animal {
void unique() { public void makeSound() {
[Link]("Child Unique"); [Link]("Woof!");
} }
@Override
void special() { final public void displayAge() {
[Link]("Child Special"); [Link]("Age: " + age);
} }
} public static void main(String[] args) {
public class Main { Dog dog = new Dog();
public static void main(String[] args) [Link]();
{ Parent obj = new Child(); [Link]();
[Link](); }
} }
}
MCQ
class Vehicle { }
void start() {
[Link]("Vehicle Starting ");
S }
void drive() {
[Link]("Vehicle Driving ");
}
}
class Car extends Vehicle
{ void honk() {
[Link]("Car Honking ");
}
@Override
void drive() {
[Link]("Car Driving ");
}
}
public class Main {
public static void main(String[] args)
{ Vehicle obj = new Car();
[Link]();
[Link]();
}
public class "B" + 5 * 2);
Main { [Link](5 + 2 + "B" + 5 *
public static 2);
void [Link]("B" + 1 + 4);
main(Strin }
g[] args) }
{ System.o public class Main {
[Link]( public static void
"B" + 5 * main(String[] args)
2); { String str1 = "Java";
[Link] String str2 = "Java";
[Link](5 String str3 = new String("Java");
+ 2 + "B" + [Link](str1 == str2);
5 * 2); [Link](str1 == str3);
} [Link]([Link](str3))
} ;
public class }
Main { }
public static
void
main(Strin
g[] args)
{ System.o
[Link](
MCQ class Animal { class Animal
void sound() { { void sound() {
[Link]("Animal sound"); [Link]("Animal makes a sound");
S }
}
}
}
S
[Link]("Animal makes a { Animal animal1 = new Dog();
sound"); Animal animal2 = new Cat();
} Dog dog = new Dog();
[Link]();
} [Link]();
class Dog extends Animal ((Animal) dog).sound();
{ void sound() { ((Animal) dog).diff();
[Link]("Dog barks"); }
} }
void diff(){
[Link]("DIFF");
}
}
class Cat extends Animal {
void sound() {
[Link]("Cat meows");
}
}
MCQ class Animal {
void sound() {
public class Test {
public static void main(String[] args)
S
[Link]("Animal makes a { Animal animal1 = new Dog();
sound"); Animal animal2 = new Cat();
} Dog dog = new Dog();
[Link]();
} [Link]();
class Dog extends Animal ((Animal) dog).sound();
{ void sound() { ((Animal) dog).diff();
[Link]("Dog barks"); }
} }
void diff(){
[Link]("DIFF");
}
}
class Cat extends Animal {
void sound() {
[Link]("Cat meows");
}
}