0% found this document useful (0 votes)
6 views30 pages

Java Merged

The document discusses the types of inheritance in Java, including single, multilevel, hierarchical, multiple (via interfaces), and hybrid (also via interfaces) inheritance. It explains the concept of inheritance as a mechanism for code reuse and establishing parent-child relationships between classes. Additionally, it provides examples and important points to remember about each type of inheritance.

Uploaded by

sadhananamogange
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)
6 views30 pages

Java Merged

The document discusses the types of inheritance in Java, including single, multilevel, hierarchical, multiple (via interfaces), and hybrid (also via interfaces) inheritance. It explains the concept of inheritance as a mechanism for code reuse and establishing parent-child relationships between classes. Additionally, it provides examples and important points to remember about each type of inheritance.

Uploaded by

sadhananamogange
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

7/23/25, 3:47 PM Types of Inheritance in Java

Types of Inheritance in Java


Introduction
Inheritance in Java means one class can use the properties (like variables and methods) of
another class.
It is the fundamental concept of OOP's which helps to reuse code.
It creates a parent-child relationship, where the parent is called the superclass and the child
is called the subclass.
Click here to read more about Inheritance in Java.

There are 5 types of Inheritance in Java:


1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (not supported directly)
5. Hybrid Inheritance (not supported directly)

Single Inheritance:
Single level inheritance is a type of inheritance in which a child class inherits directly from a
single parent class.
It allows the child class to reuse the fields and methods of the parent class.

Syntax:

class ParentClass {
// Parent class code
}
class ChildClass extends ParentClass {
// Child class code
}

[Link] 1/16
7/23/25, 3:47 PM Types of Inheritance in Java

Program example:

// Parent class
class BankAccount
{
void accountType()
{
[Link]("This is a general bank account.");
}
}
// Child class
class SavingsAccount extends BankAccount
{
void interestRate()
{
[Link]("Savings account offers 4% interest.");
}
}
// Main class
public class MainApp
{
public static void main(String[] args)
{
SavingsAccount sa = new SavingsAccount();
[Link](); // Inherited method
[Link](); // Specific method
} }

Output:
This is a general bank account.
Savings account offers 4% interest.

Multilevel Inheritance:
Multilevel inheritance is a type of inheritance where a class inherits from a child class,
making a chain of inheritance.
Here, a class acts as a parent for another class, which in turn acts as a parent for a third
class.
This forms a hierarchy of classes connected through inheritance.

Syntax:
class Grandparent {
// code
}
class Parent extends Grandparent {
// code
}
class Child extends Parent {
// code
}
[Link] 2/16
7/23/25, 3:47 PM Types of Inheritance in Java

Program example:

// Grandparent class
class Animal
{
void eat()
{
[Link]("Animal is eating.");
}
}
// Parent class
class Dog extends Animal
{
void bark()
{
[Link]("Dog is barking.");
}
}
// Child class
class Puppy extends Dog
{
void weep()
{
[Link]("Puppy is weeping.");
}
}
public class MainApp
{
public static void main(String[] args)
{
Puppy p = new Puppy();
[Link](); // From Animal
[Link](); // From Dog
[Link](); // Own method
} }
[Link] 3/16
7/23/25, 3:47 PM Types of Inheritance in Java

Output:
Animal is eating.
Dog is barking.
Puppy is weeping.

Important Points to Remember:


Multilevel inheritance represents a class hierarchy with more than two levels.
The child class inherits properties from its parent class and all ancestor classes.
Supports code reuse across multiple levels.
Helps model real-world hierarchical relationships.

Hierarchical Inheritance:
Hierarchical inheritance is a type of inheritance where multiple child classes inherit from a
single parent class.
It allows multiple subclasses to share the properties and behaviors of the same parent class.
This type of inheritance is useful for creating a common base class for multiple classes.

Syntax:
class Parent {
// Parent class code
}
class Child1 extends Parent {
// Child1 specific code
}
class Child2 extends Parent {
// Child2 specific code
}

[Link] 4/16
7/23/25, 3:47 PM Types of Inheritance in Java

Program example:

// Parent class
class Vehicle
{
void fuelType()
{
[Link]("Uses fuel.");
}
}

// First child class


class Car extends Vehicle
{
void wheels()
{
[Link]("Car has 4 wheels.");
}
}

// Second child class


class Bike extends Vehicle
{
void handleType()
{
[Link]("Bike has a handlebar.");
}
}

public class MainApp


{
public static void main(String[] args)
{
Car c = new Car();
[Link](); // Inherited from Vehicle
[Link](); // Car specific

Bike b = new Bike();


[Link](); // Inherited from Vehicle
[Link](); // Bike specific
}
}

[Link] 5/16
7/23/25, 3:47 PM Types of Inheritance in Java

Output:
Uses fuel.
Car has 4 wheels.
Uses fuel.
Bike has a handlebar.

Important Points to Remember:


Hierarchical inheritance allows code reuse through a shared parent class.
Each subclass gets its own copy of the parent class’s properties and methods.
It promotes loose coupling by separating shared logic into a base class.
It's useful when multiple classes share common behavior and properties.

Multiple Inheritance:

(commonly known as the "Diamond Problem"). However, it can be achieved using interfaces.

Multiple inheritance refers to a feature where a class can inherit features (methods and
fields) from more than one parent class.
Java does not support multiple inheritance with classes directly, but it supports it through
interfaces.
This prevents conflicts and ambiguity caused by the Diamond Problem.

Syntax using interfaces:

interface A
{
void methodA();
}

interface B
{
void methodB();
}

class C implements A, B {
public void methodA()
{
[Link]("Method from interface A");
}

public void methodB()


{
[Link]("Method from interface B");
}
}

[Link] 6/16
7/23/25, 3:47 PM Types of Inheritance in Java

Program example (using interfaces):

// Interface A
interface A {
void displayA();
}

// Interface B
interface B {
void displayB();
}

// Class C implementing both interfaces


class C implements A, B {
public void displayA()
{
[Link]("Display from interface A");
}

public void displayB()


{
[Link]("Display from interface B");
}
}
public class MainApp
{
public static void main(String[] args)
{
C obj = new C();
[Link]();
[Link]();
}
}
[Link] 7/16
7/23/25, 3:47 PM Types of Inheritance in Java

Output:
Display from interface A
Display from interface B

Important Points to Remember:


Java classes cannot extend more than one class at a time.
Multiple inheritance is achieved using interfaces in Java.
This design avoids ambiguity and promotes clean architecture.
Interfaces define abstract behavior that multiple classes can implement.

Hybrid Inheritance:

Hybrid inheritance is a combination of two or more types of inheritance (e.g., single, multiple,
multilevel).
It represents a scenario where different inheritance types are combined to form a complex
hierarchy.
Java does not support hybrid inheritance with classes due to ambiguity issues but supports
it through interfaces.
Syntax using interfaces and a class
interface A {
void methodA();
}

interface B {
void methodB();
}

class C {
void methodC()
{
[Link]("Method from class C");
}
}
// Class D inherits class C and implements A and B
class D extends C implements A, B {
public void methodA() {
[Link]("Method from interface A");
}

public void methodB(){


[Link]("Method from interface B");
}
}

[Link] 8/16
7/23/25, 3:47 PM Types of Inheritance in Java

Program example (using interfaces and class):

// Interface A
interface A{
void showA();
}
// Interface B
interface B{
void showB();
}
// Class C
class C {
void showC() {
[Link]("Show from class C");
}
}
// Class D: extends C and implements A and B
class D extends C implements A, B
{
public void showA() {
[Link]("Show from interface A");
}
public void showB() {
[Link]("Show from interface B");
} }
// Main class
public class MainApp
{
public static void main(String[] args) {
C obj = new D();
[Link]();
[Link]();
[Link]();
}
}
[Link] 9/16
7/23/25, 3:47 PM Types of Inheritance in Java

Output:
Show from interface A
Show from interface B
Show from class C

Important Points to Remember:


Hybrid inheritance combines multiple types of inheritance to represent more complex
relationships.
Java does not support hybrid inheritance with classes directly.
It can be implemented safely using interfaces to avoid ambiguity.
Helps in designing systems with multiple traits and layered behaviors.

Next Topic

[Link] 10/16
7/23/25, 3:35 PM Inheritance in Java

×
Inheritance in Java
Introduction
Inheritance means acquiring the properties and behaviors of a parent class in a child class.
It allows a subclass (child class) to inherit fields and methods from a superclass (parent
class), promoting code reuse and method overriding.

Inheritance represents an IS-A relationship, also known as a parent-child relationship. It


signifies that a subclass is a type of its superclass.
For example:
A Car IS-A Vehicle.
A Dog IS-A Animal.
A Surgeon IS-A Doctor.

How to achieve inheritance in Java?


By using the extends keyword for class inheritance.
By using the implements keyword for interface inheritance.

Program 1 (using extends keyword): :

class Vehicle {
void start()
{
[Link]("Vehicle starts.");
}
}

class Car extends Vehicle {


void drive()
{
[Link]("Car drives.");

}
}

public class MainApp


{
public static void main(String[] args)
{
Car myCar = new Car();

[Link](); // inherited from Vehicle


[Link](); // specific to Car
}
}

[Link] 1/9
7/23/25, 3:35 PM Inheritance in Java

Program 2 (using implements keyword): :

interface Animal
{
void eat();
}
class Dog implements Animal
{
public void eat()
{
[Link]("Dog eats.");
}
}
public class MainApp
{
public static void main(String[] args)
{
Dog myDog = new Dog();
[Link](); // inherited from Animal

//Animal myAnimal = new Animal(); // error because we cannot create an obj


}
}

Advantages of Inheritance
Code Reusability: Inheritance allows a child class to reuse the code of its parent class.
Easy Maintenance: Changes made in the parent class automatically propagate to child
classes, making maintenance easier.
Method Overriding: Inheritance enables method overriding, allowing a child class to
provide a specific implementation of a method already defined in its parent class.
Polymorphism: Inheritance supports runtime polymorphism using method overriding.

Disadvantages of Inheritance
Tight Coupling: Inheritance creates a tight coupling between parent and child classes, if we
change the parent class, it may affect all child classes.
Increased Complexity: Inheritance can lead to complex class hierarchies, making the code
harder to understand and maintain.

[Link] 2/9
7/23/25, 3:35 PM Inheritance in Java
Types of Inheritance
There are 5 types of inheritance in Java:
1. Single Inheritance: One class inherits the properties and behaviors of one parent class.
2. Multilevel Inheritance: One class inherits the properties and behaviors of a parent class,
and that class is inherited by another class.
3. Hierarchical Inheritance: Multiple classes inherit the properties and behaviors of a single
parent class.
4. Multiple Inheritance: One class inherits the properties and behaviors of multiple classes.
(Not supported in Java directly, but can be achieved using interfaces.)
5. Hybrid Inheritance: A combination of two or more types of inheritance. (Not supported in
Java directly, but can be achieved using interfaces.)
Click Here to learn more about the types of inheritance in Java.

Important Points
Some important points to remember about inheritance in Java:
Java does not support multiple and hybrid inheritance with classes to avoid ambiguity,
such as the diamond problem.
A class can extend only one class, which is known as single inheritance.
Constructors and private members of the parent class are not inherited by the child
class.
A class can implement multiple interfaces, which is Java's way of achieving multiple
inheritance.
The super keyword is used to refer to the parent class, such as accessing parent class
methods or constructors.
The this keyword is used to refer to the current class instance, commonly used to
differentiate between instance variables and parameters.

Encapsulation in Java
Introduction
Encapsulation is the mechanism of binding data (variables) and actions (methods) into a
single unit, called a class.
Technically, every class is an example of encapsulation.

Real World Example:

A capsule in which main medicine is encapsulated

[Link] 3/9
7/23/25, 3:34 PM Encapsulation in Java

Next Topic

A car is in which engine, wheels, and other parts are encapsulated.

Java Program Example:

class Car
{
// Data members (variables)
String brand;
int speed;

// Method to display person details


void setDetails(String b, int s)
{
brand = b;
speed = s;
}
void printDetails()
{
[Link]("Brand : " + brand);
[Link]("Speed : " + speed);
}
}

public class Main


{
public static void main(String[] args)
{
// Creating object
Car c = new Car();

// Calling method
[Link]("Tata", 100);
}
}

[Link] 4/12
7/23/25, 3:34 PM Encapsulation in Java

OUTPUT:
Brand : Tata
Speed : 100

Explanation:
Person class contains both data ( name , age ) and method ( displayInfo() ).
Everything is inside one unit (class) — this is the essence of encapsulation.

Note:

Rules for Encapsulation :-


1. Private Variables :
Declare variables as private so that they cannot be accessed directly from outside the
class.
2. Public Getter & Setter Methdos :
Provide public getter and setter methods to access and modify the private variables.

Actual/Proper Encapsulated Java Program Example :-

class Car
{
// Private data members (encapsulated)
private String brand;
private int speed;

// Public setter for brand


public void setBrand(String brand)
{
[Link] = brand;
}

// Public getter for brand


public String getBrand()
{
return brand;
}

// Public setter for speed


public void setSpeed(int speed)
{
// Optional: simple validation
if (speed >= 0)
{
[Link] = speed;
} }

[Link] 5/12
7/23/25, 3:34 PM Encapsulation in Java

// Public getter for speed


public int getSpeed()
{
return speed;
}

// Method to print car details


public void printDetails()
{
[Link]("Brand : " + brand);
[Link]("Speed : " + speed);
}
}

public class MainApp


{
public static void main(String[] args)
{
Car c = new Car();

// Setting values using setters


[Link]("Tata");
[Link](100);

// Printing car details


[Link]();
}
}

Output:
Speed : Tata
Speed : 100

Use of Encapsulation :-
1. Protects data: Hides data from direct access using private variables.
2. Controls data access: Provides controlled access through public getters and setters.
3. Allows data validation: Enables validation before updating variables (e.g., checking valid
input).
4. Improves code maintainability: Keeps internal implementation hidden, making changes
easier.
5. Enhances flexibility: Internal logic can change without affecting external code.
6. Prevents unauthorized or accidental modifications: Limits who and how data can be
changed.

[Link] 6/12
7/23/25, 3:33 PM Abstraction in Java

Abstraction in Java
Introduction
Abstraction is a concept of :
hiding internal implementation details and howing only the essential features to the
user.

Real World Example


When you drive a car, you only need to know how to operate the
steering wheel, pedals and gear shift. You don't need to
understand how the engine works or how the brakes are
designed.

How to achieve Abstraction :-


We can achieve Abstraction by two ways:
Using Abstract Classes
Using Interfaces
Abstract Methods :-
Introduction
An abstract method is a method that is declared without an implementation (no
method body).
It only provides the method signature and forces subclasses to provide the actual
implementation.
Declared using the abstract keyword.

Syntax & Example :


Syntax : abstract returnType methodName(parameters);
Example : abstract void makeSound(); // Abstract method – no body

Rules of Abstract Method :


No method body – ends with a semicolon (;).
Must be declared inside an abstract class or interface.
A class that contains an abstract method must be declared abstract.
Abstract methods must be overridden by subclasses, unless the subclass is also
abstract.
Cannot be private, static or final — because it must be overridden.

Abstract Class :-
Introduction
An abstract class in Java is a class that is declared using the abstract keyword.
It can contain a mix of abstract methods (without body) and concrete methods (with
body).
It cannot be instantiated (you cannot create objects of it).

[Link] 1/11
7/23/25, 3:33 PM Abstraction in Java

Syntax & Example :


Syntax:
abstract class ClassName {
// abstract method
abstract void makeSound();

// concrete method
void sleep() {
[Link]("Sleeping...");
}
}

Example:

abstract class Car


{
// Abstract method (must be implemented by subclasses)
abstract void startEngine();

// Concrete method
void fuelType()
{
[Link]("This car uses petrol or diesel.");
}
}
class Sedan extends Car
{
@Override
void startEngine()
{
[Link]("Sedan engine started with key ignition.");
}
}

Rules of Abstract Class :


Must be declared using the abstract keyword.
Can contain both abstract and concrete methods.
Cannot be instantiated directly.
Subclass must override all abstract methods or be declared abstract itself.
Can have constructors, static methods and final methods.
Can extend another class and implement interfaces.

[Link] 2/11
7/23/25, 3:33 PM Abstraction in Java

Program Without Abstraction

class Car
{
int no_of_tyres = 4;

void displayTyres()
{
[Link]("Car has " + no_of_tyres + " tyres.");
}

void start(){
[Link]("Car starts with a key ignition.");
}
}

// Scooter class without abstraction


class Scooter
{
int no_of_tyres = 2;

void displayTyres() {
[Link]("Scooter has " + no_of_tyres + " tyres.");
}

void start() {
[Link]("Scooter starts with a kick or self-start.");
}
}

// Main class to run the program


public class MainApp

{
public static void main(String[] args)
{
Car myCar = new Car();
[Link]();
[Link]();

[Link]();

Scooter myScooter = new Scooter();


[Link]();
[Link]();
}
}

[Link] 3/11
7/23/25, 3:33 PM Abstraction in Java

Output:
Car has 4 tyres.
Car starts with a key ignition.

Scooter has 2 tyres.


Scooter starts with a kick or self-start.

Disadvantages of Not Using Abstraction


1. No Polymorphism:
We can’t use a common parent reference to refer to multiple types of vehicles.
Example:
Vehicle vehicle = new Car(); // Not possible, because there is no common Vehicle type
This limits flexibility and makes it hard to treat Car and Scooter uniformly.
2. Code Duplication:
Common logic like displayTyres() is repeated in every class ( Car , Scooter , etc.).
In a larger system, this leads to duplicate code, harder maintenance, and higher chances
of bugs.
3. No Method Enforcement:
There is no guarantee that all vehicle-related classes will implement essential methods
like start().
A developer might forget to add a critical method in a new class like Bike, leading to
incomplete functionality.
4. Poor Scalability:
As the project grows and more vehicle types are added, maintaining consistency
becomes harder.
Any change in shared logic (e.g., tyre display format) needs to be updated in every
individual class, increasing maintenance overhead.
5. No Common Structure or Contract:
Without a common abstract class or interface, there’s no standard structure that all
vehicle classes must follow.
This leads to inconsistent design and makes collaboration or team development harder.

[Link] 4/11
7/23/25, 3:33 PM Abstraction in Java

Program Using Abstraction

// Abstract class used to remove code duplication and enforce method structure
abstract class Vehicle
{
int no_of_tyres;

// Common method to avoid duplication (removes disadvantage #2)


void displayTyres()
{
[Link]("This vehicle has " + no_of_tyres + " tyres.");
}

// Abstract method to enforce implementation in all subclasses (removes disadvan


abstract void start();
}

// Car class extends abstract class and provides its own implementation
class Car extends Vehicle
{
Car()
{
no_of_tyres = 4;
}

// Required by abstract class - enforces structure (removes disadvantage #3)


@Override
void start()
{
[Link]("Car starts with key ignition.");
}
}

// Scooter class also extends abstract class


class Scooter extends Vehicle
{
Scooter()
{
no_of_tyres = 2;
}

@Override
void start()
{
[Link]("Scooter starts with kick or self-start.");
}
}

// Main class to test polymorphism and abstraction


public class Main

[Link] 5/11
7/23/25, 3:33 PM Abstraction in Java

{
public static void main(String[] args)
{
// Using polymorphism (removes disadvantage #1)
Vehicle myVehicle1 = new Car();
[Link]();
[Link]();

[Link]();

Vehicle myVehicle2 = new Scooter();


[Link]();
[Link]();

// Easier to scale and add new vehicle types consistently (removes disadvant
}
}

Output:
This vehicle has 4 tyres.
Car starts with key ignition.

This vehicle has 2 tyres.


Scooter starts with kick or self-start.

Method Overriding in Java


Introduction
Method Overriding is a way (or mechanism or form) to achieve runtime polymorphism
It is a feature in Java that allows the child class to write its own implementation of a method
that is already present in the parent class.

The JVM determines which method to execute at runtime, based on the object type (not the reference
type).

Rules of Method Overriding :-


The methods must have the same name.
The method must be in different class or in subclass.
All the method parameters list must be same:
Number of parameters
Type of parameters
Order of parameters
Should follow IS-A relationship (Inheritance).

[Link] 6/11
7/23/25, 3:32 PM Method Overriding in Java

Example :-
class Bank {
double getInterestRate()
{
return 0.0;
}
}

class SBI extends Bank {


@Override
double getInterestRate()
{
return 6.5;
}
}

class HDFC extends Bank {


@Override
double getInterestRate()
{
return 7.0;
}
}

class ICICI extends Bank {


@Override
double getInterestRate()
{
return 6.8;
}
}

public class Main {


public static void main(String[] args)
{
Bank b1 = new SBI();
Bank b2 = new HDFC();
Bank b3 = new ICICI();

[Link]("SBI Interest Rate: " + [Link]() + "%");


[Link]("HDFC Interest Rate: " + [Link]() + "%");
[Link]("ICICI Interest Rate: " + [Link]() + "%");
}
}

[Link] 1/9
7/23/25, 3:32 PM Method Overriding in Java

Output:
SBI Interest Rate: 6.5%
HDFC Interest Rate: 7.0%
ICICI Interest Rate: 6.8%

Advantages of Method Overriding :-


1. Runtime Polymorphism::
Allows Java to decide at runtime which method to execute, enabling flexible and
dynamic behavior.

2. Improves Code Reusability:


Reuses method names from the parent class while allowing customized behavior in the
child class.
3. Supports Inheritance:
Strengthens the use of inheritance by enabling subclasses to modify or enhance the
behavior of parent class methods.
4. Better Readability and Maintainability:
Makes the code more logical and organized when different classes handle behavior in
their own way.
5. Encourages Consistency::
Keeps method names the same across class hierarchies, promoting consistency in
design.
6. Useful in Frameworks & Libraries::
Commonly used in Java frameworks (like Spring, Hibernate) where parent classes define
default behavior and subclasses override as needed.

Important Points
Some important points to remember about method overriding in Java:
1. Method overriding requires the subclass method to have the same name, return type,
and parameter list as the superclass method.
2. The overriding method must be in a subclass, not in the same class.
3. The access modifier of the overriding method cannot be more restrictive than that of the
overridden method.
(For example, if the parent method is public, the overriding method cannot be private.)

// Valid override
protected void display() {}

// Invalid override (if superclass method is public)


private void display() {}
4. Static methods, constructors, and the main method cannot be overridden.
5. Methods marked as final, static, or private cannot be overridden.
6. The overriding method can throw only the same or narrower checked exceptions than
the overridden method.
7. The @Override annotation is recommended to avoid mistakes and improve code
readability.

[Link] 2/9
7/23/25, 3:32 PM Method Overriding in Java

@Override
void methodName() {
// implementation
}

Method Overloading in Java


Introduction
Method Overloading is a way (or mechanism or form) to achieve compile-time
polymorphism
It is a feature in Java that allows a class to have more than one method with the same name,
but different parameters (number, type, or order of parameters).
The compiler determines which method to execute at compile time, based on the method
signature.

Rules of Method Overloading :-


All overloaded methods must have the same name.
All the methods should be in same class or in subclass.
All the method parameters list must be different:
Number of parameters
Type of parameters
Order of parameters

Example :-

class Calculator {
int add(int a, int b)
{
return a + b;
}

double add(double a, double b) {


return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
} }
public class MainApp {
public static void main(String[] args) {
Calculator calc = new Calculator();

// Calling overloaded methods


int result1 = [Link](10, 20);
double result2 = [Link](5.5, 4.5);
int result3 = [Link](1, 2, 3);

[Link] 3/9
7/23/25, 3:31 PM Method Overloading in Java

// Printing the results


[Link]("Result of add(int, int): " + result1);
[Link]("Result of add(double, double): " + result2);
[Link]("Result of add(int, int, int): " + result3);
}
}

Output:
Result of add(int, int): 30
Result of add(double, double): 10.0
Result of add(int, int, int): 6

Note :

Advantages of Method Overloading :-


1. Increased Readability:
Using the same method name for similar actions makes the code easier to understand.
2. Faster Execution (at Compile Time):
Since the method to be called is determined at compile time, it improves performance
over runtime decisions (like in method overriding).
3. Easy Maintenance:
Having logically grouped methods under one name makes code more organized and
easier to maintain.
4. Encourages DRY Principle (Don't Repeat Yourself):
Avoids writing similar code in different method names for similar logic.
5. Helps in Testing:
Easier to write unit tests for overloaded methods as they often represent the same action
with varied input.

6. Cleaner API Design:


When designing libraries or APIs, overloading allows a consistent interface for different data
inputs.

Important Points
Some important points to remember about method overloading in Java:

1. Method overloading does not depend on return type, it depends only on the parameter
list.
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } //Valid overload

[Link] 4/9
7/23/25, 3:31 PM Polymorphism in Java

2. Main method can also be overloaded in Java.

public static void main(String[] args)


{
[Link]("Main method with String[]");
}
public static void main(int[] args)
{
[Link]("Main method with int[]");
}

3. Constructors can also be overloaded.

class Student
{
Student() {}
Student(String name) {}
Student(String name, int age) {}
}

4. Access modifiers (e.g., public, private) can be different.

public void show() {}


private void show(int a) {} //Valid overload

5. Static methods can be overloaded.

static void display() {}

Polymorphism in Java
Introduction
Polymorphism is one of the main concepts of Object-Oriented Programming (OOP) in Java.
Poly → many, Morph → forms; so Polymorphism means "many forms".
It means the ability of a single entity (method, object, or operator) to behave in multiple
ways.
Java uses polymorphism to let us write flexible and reusable code.

Real-world Examples :-
A person: acts as a teacher, father, son — different roles.
Water: takes shape of the container it’s in.
Sound: same sound word used in different tones.

Advantage of Polymorphism :-
Increases flexibility and reusability.
Allows code extensibility without modifying existing code.
Supports single task, multiple implementations.
Enhances maintainability and scalability.

[Link] 1/8
7/23/25, 3:31 PM Polymorphism in Java

Types of Polymorphism in Java :-


1. Compile-Time Polymorphism
It is also known as Static Binding or Early Binding.

It is achieved by Method Overloading or Operator Overloading.

In compile-time polymorphism, the Java compiler decides at compile time which


overloaded method or operator to invoke based on the method signature and reference
type.

Program (Method Overloading):

class Calculator
{
void add(int a, int b)
{
[Link](a+b);
}

void add(double a, double b)


{
[Link](a+b);
}
}

Here:
Calculator calc = new Calculator(); // Reference type = Calculator
[Link](5, 10); // method signature = add(int, int) → decided at compile-time

Click here to read more about Method Overloading

Runtime Polymorphism
It is also known as Dynamic Binding or Late Binding.

It is achieved by Method Overriding.

In runtime polymorphism, the JVM (Java Virtual Machine) decides at runtime which
overridden method to invoke based on the actual object (not the reference type).

Program (Method Overriding):

class Animal {
void makeSound() {
[Link]("Some generic sound");
}
}

class Dog extends Animal {


void makeSound() {
[Link]("Dog barks");
}
}

[Link] 2/8
7/23/25, 3:31 PM Polymorphism in Java

Here:
Animal obj = new Dog(); // Reference type = Animal, Object type = Dog
[Link](); // Method decided at runtime → calls Dog's makeSound()

Click here to read more about Method Overriding


Important Points
Some important points to remember about polymorphism in Java:
1. Polymorphism is mainly achieved through method overloading and method overriding.
Overloading → Compile-time polymorphism
Overriding → Runtime polymorphism
2. Polymorphism supports the Open/Closed Principle.
Code is open for extension but closed for modification.
3. Polymorphism helps reduce code duplication by reusing the same interface or method
name across different types.
4. Upcasting enables runtime polymorphism.
Parent class reference can hold a child class object.
Example:

Animal myDog = new Dog();

[Link] 3/8
7/23/25, 3:31 PM Polymorphism in Java

[Link] 4/8

You might also like