0% found this document useful (0 votes)
12 views23 pages

Notes OOP Unit 3 Inheritance and Polymorphism

Notes OOP

Uploaded by

abhirajukirde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views23 pages

Notes OOP Unit 3 Inheritance and Polymorphism

Notes OOP

Uploaded by

abhirajukirde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit No: III

Inheritance & Polymorphism


1.1 Inheritance:Introduction, Need of Inheritance, Types of Inheritance, Benefits of Inheritance, Cost of
Inheritance, 1.2 Constructors in Derived Classes 1.3 Method Overriding 1.4 Abstract Classes
1.5 Interfaces. 1.6 Polymorphism and Software Reuse: Introduction, Types of Polymorphism,
Compile-Time and Run-Time Polymorphism 1.7 Mechanisms for Software Reuse, Efficiency and
Polymorphism.

1.1 Inheritance:

Introduction:

●​ Inheritance is a fundamental concept in OOP(Object-Oriented Programming).


●​ It is the mechanism by which one class is allowed to inherit the features(fields and
methods) of another class.
●​ Inheritance means creating new classes based on existing ones. A class that inherits from
another class can reuse the methods and fields of that class.
●​ Class: Class is a set of objects that share common characteristics/ behavior and common
properties/ attributes. Class is not a real-world entity. It is just a template or blueprint or
prototype from which objects are created.
●​ Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
●​ Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
●​ The extends keyword is used for inheritance .
●​ It enables the subclass to inherit the fields and methods of the superclass.
●​ When a class extends another class, it means it inherits all members (fields and methods)
of the parent class and the subclass can also override or add new functionality to them.

Syntax
class ChildClass extends ParentClass
{
// Additional fields and methods
}

Example:

●​ In the following example, Animal is the base class and


Dog, Cat and Cow are derived classes that extend the
Animal class.

1
class Animal { // Parent class public class Main {
void sound() { public static void main(String[] args) {
System.out.println("Animal makes a sound"); Animal a;
} a = new Dog();
} a.sound();
class Dog extends Animal { // Child class a = new Cat();
void sound() { a.sound();
System.out.println("Dog barks"); a = new Cow();
} a.sound();
} }
class Cat extends Animal { // Child class }
void sound() {
System.out.println("Cat meows"); Output:
} Dog barks
} Cat meows
class Cow extends Animal { // Child class Cow moos
void sound() { Explanation:
System.out.println("Cow moos");
} ●​ Animal is the base class.
} ●​ Dog, Cat and Cow are derived classes that
extend Animal class and provide specific
implementations of the sound() method.

Need of Inheritance:

1.​ Code Reusability


○​ Allows child classes to reuse methods and properties of parent classes.
○​ Reduces duplication and saves development time.
2.​ Improved Maintainability
○​ Common logic is centralized in the parent class.
○​ Easier to update or fix bugs in one place.
3.​ Extensibility
○​ Child classes can add new features or override existing ones.
○​ Promotes scalable and flexible design.
4.​ Logical Hierarchy
○​ Models real-world relationships (e.g., Animal → Dog, Cat).
○​ Makes code more intuitive and organized.
5.​ Polymorphism Support
○​ Enables method overriding and dynamic method dispatch.
○​ Enhances runtime flexibility.
6.​ Reduced Redundancy
○​ Avoids rewriting the same code in multiple classes.
○​ Promotes cleaner and more efficient codebase.
7.​ Encapsulation of Common Behavior
○​ Shared behavior is grouped in a base class.
○​ Encourages modular design.

2
Types of Inheritance:

Below are the different types of inheritance:

●​ Single Inheritance
●​ Multilevel Inheritance
●​ Hierarchical Inheritance
●​ Multiple Inheritance
●​ Hybrid Inheritance

1. Single Inheritance

In single inheritance, a sub-class is derived from


only one super class. It inherits the properties and
behavior of a single-parent class. Sometimes, it is
also known as simple inheritance.

Syntax:
class BaseClass
{
// Members and methods of the base class
};
class DerivedClass extends BaseClass
{
// Members and methods of the derived class
// Inherits from BaseClass
};
//Super class // Creating object of subclass invokes base class
class Vehicle { constructor
Vehicle() { Car obj = new Car();
System.out.println("This is a Vehicle"); }
} }
}
Output
// Subclass This is a Vehicle
class Car extends Vehicle { This Vehicle is Car
Car() {
System.out.println("This Vehicle is Car"); Explanation:
} ●​ This program shows inheritance between a
} parent class (Vehicle) and a child class (Car).
public class Test { ●​ When a Car object is created, Java first calls
public static void main(String[] args) { the Vehicle constructor automatically.
●​ This is called constructor chaining, and it
ensures proper initialization.
●​ Both constructors print messages, showing the
order of execution.

3
2. Multilevel Inheritance:
●​ In multilevel inheritance, a class is derived from a
class which is already derived from another class. It
forms a chain of inheritance.
●​ Multilevel Inheritance is a type of inheritance in
C++ where one class inherits another class, which in
turn is derived from another class. It is known as
multi-level inheritance as there are more than one
level of inheritance.
●​ For example, if we take Grandfather as a base class
then Father is the derived class that has features of
Grandfather and then Child is the also derived class
that is derived from the sub-class Father which
inherits all the features of Father.

Syntax:
class A class C extends B
{ {
// Base class // Derived class
} }
class B extends A
{
// Intermediate class
}

Example:

class Animal { Dog obj = new Dog();


Animal() { }
System.out.println("This is an Animal"); }
}
} Output:
class Mammal extends Animal { This is an Animal
Mammal() { This Animal is a Mammal
System.out.println("This Animal is a This Mammal is a Dog
Mammal");
} Explanation:
} This example shows a three-level inheritance
class Dog extends Mammal { chain. When a Dog object is created, constructors
Dog() { of all parent classes are called in order—starting
System.out.println("This Mammal is a from Animal, then Mammal, and finally Dog.
Dog"); This demonstrates constructor chaining across
} multiple levels.
}

public class Test {


public static void main(String[] args) {

4
3.Hierarchical Inheritance:
●​ Hierarchical inheritance is a type of inheritance in Object-Oriented Programming (OOP)
where multiple derived classes (subclasses) inherit from a single base class (superclass).
●​ This creates a tree-like structure where one parent class has several child classes, each
potentially adding its own unique functionalities while sharing common attributes and
methods from the base class
Syntax:
class Parent {
// Base class
}

class Child1 extends Parent {


// First subclass
}

class Child2 extends Parent {


// Second subclass
}

Example:

class Shape { public class Test {


Shape() { public static void main(String[] args) {
System.out.println("This is a Shape"); Circle c = new Circle();
} Square s = new Square();
} }
}
class Circle extends Shape {
Circle() { Output:
System.out.println("This Shape is a
Circle"); This is a Shape
} This Shape is a Circle
} This is a Shape
This Shape is a Square
class Square extends Shape {
Square() { Explanation:
System.out.println("This Shape is a Both Circle and Square inherit from the
Square"); same parent class Shape. When objects of
} each subclass are created, the Shape
}
constructor is called first, followed by the
respective subclass constructor.

5
4.Multiple Inheritance:(Covers point 1.5 Interface also)
●​ In object-oriented programming (OOP), multiple inheritance refers to
a feature where a class can inherit characteristics (methods and
properties) from more than one parent class.
●​ This allows a child class to combine and reuse functionality from
multiple sources.
●​ In Java, multiple inheritance of classes is not supported to avoid
ambiguity and complexity—especially the infamous diamond
problem.
●​ However, Java does support multiple inheritance through interfaces,
which allows a class to inherit behavior from multiple sources
without the pitfalls of class-based multiple inheritance.

Why Java Avoids Class-Based Multiple Inheritance

●​ Ambiguity: If two parent classes have methods with the same signature, the compiler
can't decide which one to use.
●​ Diamond Problem: When two classes inherit from the same superclass and a third class
inherits from both, method resolution becomes unclear.
●​ Simplicity: Java favors clean, maintainable code through single inheritance and
interface-based design.

●​ Syntax:

interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() { }
public void methodB() { }
}

Imagine a Smartwatch that inherits features from both a Watch and a Fitness Tracker.
Parent Class 1: Watch
●​ Shows time

●​ Has alarm

6
●​ Stopwatch feature

Parent Class 2: Fitness Tracker


●​ Counts steps

●​ Measures heart rate


●​ Tracks sleep

Child Class: Smartwatch

●​ Inherits time-related features from Watch


●​ Inherits health-related features from Fitness Tracker
●​ Adds its own features like notifications, music control, etc

Example:

// Interface 1: Watch // Main class to test functionality


interface Watch { public class MultipleInheritanceDemo {
void showTime(); public static void main(String[] args) {
void setAlarm(); SmartWatch myWatch = new SmartWatch();
} // Using Watch features
// Interface 2: FitnessTracker myWatch.showTime();
interface FitnessTracker { myWatch.setAlarm();
void trackSteps();
void measureHeartRate(); // Using FitnessTracker features
} myWatch.trackSteps();
// Class implementing both interfaces myWatch.measureHeartRate();
class SmartWatch implements Watch, FitnessTracker {
// Implementing Watch methods // Using SmartWatch-specific feature
public void showTime() { myWatch.
System.out.println("Showing current time: 10:47 playMusic();
AM"); }
} }
public void setAlarm() {
System.out.println("Alarm set for 6:00 AM");} Output:
// Implementing FitnessTracker methods Showing current time: 10:47 AM
Alarm set for 6:00 AM
public void trackSteps() {
Tracking steps: 5,432 steps today
System.out.println("Tracking steps: 5,432 steps Measuring heart rate: 72 bpm
today"); Playing music: 'Shape of You' by Ed Sheeran
}
public void measureHeartRate() { Explanation:
System.out.println("Measuring heart rate: 72 SmartWatch implements two interfaces: Watch and
bpm"); FitnessTracker.

7
} Each interface defines two methods, and SmartWatch
// SmartWatch-specific method provides concrete implementations for all four.
public void playMusic() { Additionally, SmartWatch has its own method
System.out.println("Playing music: 'Shape of playMusic(), showcasing how a class can extend
You' by Ed Sheeran"); functionality beyond inherited behavior.
} In main(), all methods are called sequentially,
} demonstrating how multiple inheritance via interfaces
allows a class to combine diverse behaviors.

Example 2:

interface Printable { public class Test {


void print(); public static void main(String[] args) {
} MultiFunctionPrinter mfp = new
MultiFunctionPrinter();
interface Scannable { mfp.print();
void scan(); mfp.scan();
} }
}
class MultiFunctionPrinter implements
Printable, Scannable { Output:
public void print() { Printing document
System.out.println("Printing document"); Scanning document
}
Explanation:
public void scan() { Here, MultiFunctionPrinter implements two
System.out.println("Scanning interfaces: Printable and Scannable. This is
document"); Java’s way of achieving multiple
} inheritance—allowing a class to inherit
} behavior from multiple sources without
ambiguity.

5. Hybrid Inheritance :
●​ Hybrid inheritance is a combination of two or more
types of inheritance (like single, multiple,
hierarchical, or multilevel) in one program.
●​ It’s often used to demonstrate how complex
relationships between classes can be structured.
●​ Since Java doesn’t support multiple inheritance with
classes (to avoid ambiguity), hybrid inheritance in
Java is typically achieved using interfaces.

8
Syntax:
Interface A

Class B (implements A)

Class C (extends B)

Class D (extends C, implements Interface E)

Example:

// Interface A public void playMusic() {


interface Device { System.out.println("Playing music from
void powerOn(); SmartPhone.");
} }

// Interface B void browseInternet() {


interface MusicPlayer { System.out.println("Browsing internet...");
void playMusic(); }
} }

// Base class // Main class


class Electronic { public class HybridInheritanceDemo {
void charge() { public static void main(String[] args) {
System.out.println("Charging device..."); SmartPhone sp = new SmartPhone();
} sp.charge(); // From Electronic
} sp.powerOn(); // From Device interface
sp.playMusic(); // From MusicPlayer
// Intermediate class interface
class Phone extends Electronic implements
Device {
public void powerOn() {
System.out.println("Phone is powered on.");
} Output:
} Charging device...
Phone is powered on.
// Derived class Playing music from SmartPhone.
class SmartPhone extends Phone implements Browsing internet...
MusicPlayer {

sp.browseInternet(); //
SmartPhone-specific
}
}

9
●​ Diamond Problem:
○​ The primary problem with multiple inheritance is that it has the potential to create
ambiguities in child classes.
○​ In a 1995 overview whitepaper, Java lead designer James Gosling stated that the
issues with multiple inheritance were one of the motivations for the creation of
Java.
○​ The difficulties inherent in multiple inheritance are most clearly seen in the
diamond problem. In the diamond problem, parent class A has two distinct child
classes B and C; that is, child classes B and C extend class A.
○​ Now we create a new child class D, which extends both class B and class C. Note
that we have multiple inheritance (D extends B and C), hierarchical inheritance (B
and C extend A), and multilevel inheritance (D extends A, B, and C).
○​ In the diamond problem, child classes B and C inherit a method from parent class
A. Both B and C override the inherited method. But the new methods in B and C
conflict with each other.
○​ Ultimate child class D inherits the two independent and conflicting methods from
its multiple parents B and C. It is unclear which method class D should use, so
there is ambiguity. Other OOP programming languages implement various
methods for addressing the multiple inheritance ambiguity.
○​ Multiple inheritance in programming is a feature where a class can inherit
properties and methods from more than one parent class. This allows a class to
combine the features and behaviors of multiple classes into one. However, it can
lead to a lot of confusion when two parent classes have methods with the same
name, and it’s not clear which one the subclass should inherit. Therefore, some
languages like Java and C# do not support multiple inheritance, while others like
C++ and Python do. It’s a powerful tool, but it needs to be used with caution due
to its complexity.

10
Benefits of Inheritance:
1.​ Inheritance allows code reusability by enabling child classes to use methods and
properties of parent classes.
2.​ It improves maintainability since updates in the base class automatically reflect in derived
classes.
3.​ It helps organize code into a logical hierarchy that mirrors real-world relationships.
4.​ Inheritance supports extensibility, allowing new features to be added with minimal
changes.
5.​ It reduces redundancy by centralizing common code in the base class.
6.​ It enables polymorphism, allowing dynamic method dispatch and flexible behavior.
7.​ Shared behavior is encapsulated in one place, making debugging and testing easier.

Cost of Inheritance:
1.​ Inheritance creates tight coupling between base and derived classes, reducing modularity.
2.​ It can reduce flexibility, as changes in the base class may affect all subclasses.
3.​ Deep inheritance hierarchies can make code complex and harder to understand.
4.​ Constructor chaining during object creation can introduce performance overhead.
5.​ Misusing inheritance instead of composition can lead to poor software design.
6.​ Bugs in the base class can propagate to all subclasses, complicating testing.

11
1.3

1.2 Constructor in Derived Class:

1. What is a Constructor?

●​ A constructor is a special method in Java that is used to create and initialize objects of a
class. It has no return type and its name must be the same as the class name.

2. What is a Derived Class?

A derived class is a class that inherits properties and methods from another class, called the base
class. In Java, inheritance is implemented using the extends keyword.

3. How Constructors Work in Inheritance?

When an object of a derived class is created, the constructor of the base class is executed first,
followed by the constructor of the derived class. This ensures that the base part of the object is
properly initialized before the derived part.

4. Role of super() Keyword

In Java, the super() keyword is used inside a derived class constructor to explicitly call the
constructor of the base class. This call must be the first statement in the derived class constructor.

5. Default vs Parameterized Constructors

12
If the base class has a default (no-argument) constructor, Java automatically calls it when the
derived class object is created. However, if the base class only has a parameterized constructor,
then the derived class must explicitly call it using super(arguments).

6. Constructors Are Not Inherited

Constructors are not inherited from the base class to the derived class. Each class must define its
own constructor, but the derived class can call the base class constructor using super().

Example:

Example 1 Example 2
class A // Parent class
{ class Person {
public A() public Person() {
System.out.println("Default constructor in
{
Person");
System.out.println("Default constructor in }
Parent CLass");
} public Person(String name) {
public A(int a) System.out.println("Parameterized
{ constructor in Person: " + name);
System.out.println("Paremeterized }
}
constructor in Base CLass "+a);
} // Child class
} class Student extends Person {
class B extends A public Student() {
{ super(); // Calls default constructor of
public B() Person
{ System.out.println("Default constructor in
Student");
super();
}
System.out.println("Default constructor in
Derived CLass"); public Student(String name, int rollNo) {
} super(name); // Calls parameterized
public B(int a) constructor of Person
{ System.out.println("Parameterized
constructor in Student: Roll No " + rollNo);
super(10);
}
System.out.println("Paremeterized }
constructor in Derived CLass "+a);
} // Main class
} public class TestStudent {
public static void main(String[] args) {

13
class Main { Student s1 = new Student();
public static void main(String[] args) { Student s2 = new Student("Rutuja", 101);
B obj1=new B(); }
}
B obj=new B(5);
}
}
Output:
Output: Default constructor in Person
Default constructor in Parent CLass Default constructor in Student
Default constructor in Derived CLass Parameterized constructor in Person: Rutuja
Paremeterized constructor in Base CLass 10 Parameterized constructor in Student: Roll No
Parameterized constructor in Derived CLass 5 101

1.3 Method overriding :

●​ Method overriding in Object-Oriented Programming (OOP) is a language feature that


allows a subclass (or child class) to provide a specific implementation of a method that is
already defined in its superclass (or parent class).

Rules for Method Overriding

●​ The method in the subclass must have the same name as in the superclass.
●​ It must have the same return type and same parameter list.
●​ The subclass method must be accessible (same or higher visibility).
●​ The method in the superclass should not be final, static, or private.

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}

14
Key characteristics of method overriding:

●​ Inheritance:​
Method overriding can only occur within an inheritance hierarchy, where a subclass
inherits methods from a superclass.
●​ Same Signature:​
The overriding method in the subclass must have the exact same name, return type, and
parameter list (signature) as the method in the superclass it is overriding.
●​ Specific Implementation:​
The purpose of overriding is to provide a specialized or different implementation of the
inherited method within the subclass, tailoring its behavior to the specific needs of the
child class.
●​ Runtime Polymorphism:​
When a method is overridden, the version of the method executed is determined at
runtime based on the actual type of the object, not the declared type of the reference
variable. This is known as dynamic method dispatch.
●​ Restrictions:​
Certain methods, such as final, static, or private methods in some languages (like Java),
cannot be overridden. Constructors also cannot be overridden.
●​ Example:

Example 1 Example 2
// Parent class // Parent class
class Vehicle { class Animal {
void start() { void sound() {
System.out.println("Vehicle is System.out.println("Animal makes a
starting"); sound");
} }
} }

// Child class // Child class


class Car extends Vehicle { class Dog extends Animal {
@Override @Override
void start() { void sound() {
System.out.println("Car is starting System.out.println("Dog barks");
with a key"); }
} }
}
// Main class
// Main class public class TestOverride {
public class TestOverride2 { public static void main(String[] args) {
public static void main(String[] args) { Animal a = new Dog(); // Parent
Vehicle v = new Car(); // Parent reference, child object

15
reference, child object a.sound(); // Output: Dog
v.start(); // Output: Car is barks
starting with a key }
} }
}

Output: Output:
Car is starting with a key Dog barks

1.4 Abstract class:

1. What is an Abstract Class?

●​ An abstract class is a class that cannot be instantiated (you can't create objects of it).
●​ It is meant to be extended by other classes.
●​ It may contain abstract methods (without body) and concrete methods (with body).

2. Why Use Abstract Classes?

●​ Abstract classes are used when you want to define a common structure or template for all
subclasses, but leave some methods to be implemented by the child classes.

Syntax:
abstract class ClassName {
// Concrete method
void regularMethod() {
System.out.println("This is a regular method.");
}
// Abstract method (no body)
abstract void abstractMethod();
}

3.Benefits
1.​ Encapsulation of Common Behavior
●​ Abstract classes allow you to define shared methods (like playmusic()) that all
subclasses can inherit.
●​ Promotes code reuse and avoids duplication.

16
2.​ . Enforcing a Contract
●​ Abstract methods (like drive()) must be implemented by subclasses.
●​ This ensures a consistent interface across different implementations.
3.​ Polymorphism Support
●​ You can use abstract class references to point to subclass objects.
●​ Enables flexible and dynamic method calls (Car obj = new Fortuner();).
4.​ Partial Implementation
●​ Unlike interfaces, abstract classes can provide some implementation.
●​ Useful when you want to offer default behavior while still requiring customization.
5.​ Improved Code Organization
●​ Helps in structuring large applications by grouping related classes under a common
abstract parent.
●​ Makes the codebase easier to understand and maintain.
6.​ Foundation for Inheritance
●​ Abstract classes serve as a base class for other classes.
●​ Encourages a logical hierarchy and promotes object-oriented design principles.

Example:
abstract class Car Output:
{ Can Drive...
public abstract void drive(); Play Music
void playmusic()
{
Car is an abstract class.
System.out.println("Play Music");
}
drive() is abstract → no body, must be
}
overridden.
class Fortuner extends Car playmusic() is a regular method →
{ already defined.
public void drive() Fortuner is a subclass of Car.
{ It implements the abstract method drive().
System.out.println("Can Drive...");
}
}
class Main {
public static void main(String[] args) {
Car obj=new Fortuner();
obj.drive();
obj.playmusic();
}
}
1.6 Polymorphism:
★​ Introduction:

17
○​ Polymorphism in Java is one of the core concepts in object-oriented programming
(OOP) that allows objects to behave differently based on their specific class type.
○​ The word polymorphism means having many forms, and it comes from the Greek
words poly (many) and morph (forms), this means one entity can take many
forms.
○​ In Java, polymorphism allows the same method or object to behave differently
based on the context, specially on the project's actual runtime class.

Key features of polymorphism:

●​ Multiple Behaviors: The same method can behave differently depending on the object
that calls this method.
●​ Method Overriding: A child class can redefine a method of its parent class.
●​ Method Overloading: We can define multiple methods with the same name but different
parameters.
●​ Runtime Decision: At runtime, Java determines which method to call depending on the
object's actual class.

Example:Consider a person who plays different roles in life, like a father, a husband, and
an employee. Each of these roles defines different behaviors of the person depending on
the object calling it.

// Base class Person System.out.println("I am a father.");


class Person { }
}
// Method that displays the
// role of a person public class Main {
void role() { public static void main(String[] args) {
System.out.println("I am a person.");
} // Creating a reference of type Person
} // but initializing it with Father class
object
// Derived class Father that Person p = new Father();
// overrides the role method
class Father extends Person { // Calling the role method. It calls the
// overridden version in Father class
// Overridden method to show p.role();
// the role of a father }
@Override }
void role() {

Output

18
I am a father.

Why Use Polymorphism In Java?

Using polymorphism in Java has many benefits which are listed below:

●​ Code Reusability: Polymorphism allows the same method or class to be used with
different types of objects, which makes the code more useable.
●​ Flexibility: Polymorphism enables object of different classes to be treated as objects of a
common superclass, which provides flexibility in method execution and object
interaction.
●​ Abstraction: It allows the use of abstract classes or interfaces, enabling you to work with
general types (like a superclass or interface) instead of concrete types (like specific
subclasses), thus simplifying the interaction with objects.
●​ Dynamic Behavior: With polymorphism, Java can select the appropriate method to call
at runtime, giving the program dynamic behavior based on the actual object type rather
than the reference type, which enhances flexibility.

Types of Polymorphism in Java


In Java Polymorphism is mainly divided into two types:

1.​ Compile-Time Polymorphism (Static)


2.​ Runtime Polymorphism (Dynamic)

1. Compile-Time Polymorphism

19
Compile-Time Polymorphism in Java is also known as static polymorphism and also known as
method overloading. This happens when multiple methods in the same class have the same name
but different parameters.But Java doesn't support the Operator Overloading.

Method Overloading

Method overloading in Java means when there are multiple functions with the same name but
different parameters then these functions are said to be overloaded. Functions can be overloaded
by changes in the number of arguments or/and a change in the type of arguments.

// Method overloading By using // Returns product of double numbers


// Different Types of Arguments return a * b;
}
// Class 1 }
// Helper class // Class 2
class Helper { // Main class
class Geeks
// Method with 2 integer parameters {
static int Multiply(int a, int b) // Main driver method
{ public static void main(String[] args) {
// Returns product of integer numbers
return a * b; // Calling method by passing
} // input as in arguments
// Method 2 System.out.println(Helper.Multiply(2, 4));
// With same name but with 2 double System.out.println(Helper.Multiply(5.5,
parameters 6.3));
static double Multiply(double a, double b) }
{ }
Output
8
34.65

20
Explanation: The Multiply method is overloaded with different parameter types. The compiler
picks the correct method during compile time based on the arguments.

2. Runtime Polymorphism

●​ Runtime Polymorphism in Java known as Dynamic Method Dispatch. It is a process in


which a function call to the overridden method is resolved at Runtime.
●​ This type of polymorphism is achieved by Method Overriding.
●​ Method overriding, on the other hand, occurs when a derived class has a definition for
one of the member functions of the base class. That base function is said to be
overridden.

Method Overriding

●​ Method overriding in Java means when a subclass provides a specific implementation of


a method that is already defined in its superclass.
●​ The method in the subclass must have the same name, return type, and parameters as the
method in the superclass.
●​ Method overriding allows a subclass to modify or extend the behavior of an existing
method in the parent class.
●​ This enables dynamic method dispatch, where the method that gets executed is
determined at runtime based on the object's actual type.

Example: This program demonstrates method overriding in Java, where the Print() method is
redefined in the subclasses (subclass1 and subclass2) to provide specific implementations.

// Java Program for Method Overriding // Class 4


// Main class
// Class 1 class Geeks {
// Helper class
class Parent { // Main driver method
public static void main(String[] args) {
// Method of parent class
void Print() { // Creating object of class 1
System.out.println("parent class"); Parent a;
}
} // Now we will be calling print methods
// inside main() method
// Class 2 a = new subclass1();
// Helper class a.Print();
class subclass1 extends Parent {

21
a = new subclass2();
// Method a.Print();
void Print() { }
System.out.println("subclass1"); }
} Output
} subclass1
// Class 3 subclass2
// Helper class
class subclass2 extends Parent {
Explanation: In the above example, when an
// Method object of a child class is created, then the
void Print() {
System.out.println("subclass2");
method inside the child class is called. This is
} because the method in the parent class is
} overridden by the child class. This method has
more priority than the parent method inside
the child class. So, the body inside the child
class is executed.

Advantages of Polymorphism

●​ Encourages code reuse.


●​ Simplifies maintenance.
●​ Enables dynamic method dispatch.
●​ Helps in writing generic code that works with many types.

Disadvantages of Polymorphism

●​ It can make it more difficult to understand the behavior of an object.


●​ This may cause performance issues, as polymorphic behavior may require additional
computations at runtime.

1.7 Mechanisms for Software Reuse, Efficiency and Polymorphism.

❖​ Software Reuse

22
Software reuse is the practice of designing components so they can be applied in multiple
scenarios.

●​ Mechanism: Create modular, general-purpose structures that can be adapted or extended.


●​ Purpose: Reduces development time, improves consistency, and encourages scalable
design.

❖​ Software Efficiency

Efficiency in software means achieving optimal performance with minimal resources.

●​ Mechanism: Use streamlined logic, minimal redundancy, and smart resource handling.
●​ Purpose: Ensures faster execution, better responsiveness, and lower system load.

❖​ Polymorphism

Polymorphism allows different entities to respond uniquely to the same action.

●​ Mechanism: Define a common behavior and allow varied implementations.


●​ Purpose: Promotes flexibility, simplifies code management, and supports dynamic
behavior.

23

You might also like