[Go to site: main page, start]

0% found this document useful (0 votes)
4 views14 pages

Java Inheritance Polymorphism Program

The document presents a Java program that illustrates the concepts of inheritance and polymorphism through a superclass 'Employee' and its subclasses 'Manager' and 'Developer', each with distinct salary calculation methods. It explains key concepts such as method overriding, runtime polymorphism, and constructor chaining, providing examples and code snippets. The program demonstrates how the same method name can exhibit different behaviors based on the object type at runtime.

Uploaded by

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

Java Inheritance Polymorphism Program

The document presents a Java program that illustrates the concepts of inheritance and polymorphism through a superclass 'Employee' and its subclasses 'Manager' and 'Developer', each with distinct salary calculation methods. It explains key concepts such as method overriding, runtime polymorphism, and constructor chaining, providing examples and code snippets. The program demonstrates how the same method name can exhibit different behaviors based on the object type at runtime.

Uploaded by

rajitha.cse
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Program Demonstrating Inheritance and Polymorphism

This program demonstrates the concepts of Inheritance and Polymorphism in Java. It


includes a superclass 'Employee' and two subclasses 'Manager' and 'Developer'. Each
subclass calculates the salary differently to show polymorphic behavior.

Java Program Code

// Superclass: Employee
class Employee {
String name; // Common property for all employees
double baseSalary; // Base salary for all employees

// Constructor to initialize name and base salary


Employee(String name, double baseSalary) {
[Link] = name;
[Link] = baseSalary;
}

// Method to calculate salary (can be overridden by subclasses)


double calculateSalary() {
return baseSalary;
}
}

// Subclass: Manager (inherits from Employee)


class Manager extends Employee {
double bonus; // Extra pay for Manager

// Constructor for Manager


Manager(String name, double baseSalary, double bonus) {
// Call the superclass (Employee) constructor
super(name, baseSalary);
[Link] = bonus;
}

// Overriding the calculateSalary() method


// Manager’s salary = baseSalary + bonus
@Override
double calculateSalary() {
return baseSalary + bonus;
}
}
// Subclass: Developer (inherits from Employee)
class Developer extends Employee {
double projectAllowance; // Extra pay for Developer

// Constructor for Developer


Developer(String name, double baseSalary, double projectAllowance) {
// Call the superclass (Employee) constructor
super(name, baseSalary);
[Link] = projectAllowance;
}

// Overriding the calculateSalary() method


// Developer’s salary = baseSalary + project allowance
@Override
double calculateSalary() {
return baseSalary + projectAllowance;
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Create objects of Manager and Developer
// Reference type is Employee (superclass)
Employee e1 = new Manager("Raj", 50000, 10000);
Employee e2 = new Developer("Priya", 40000, 8000);

// Polymorphism: The same method name behaves differently


// depending on which object (Manager or Developer) is calling it
[Link]([Link] + "'s Salary: " + [Link]());
[Link]([Link] + "'s Salary: " + [Link]());
}
}

Step-by-Step Explanation
11️⃣Superclass Employee
Defines common properties 'name' and 'baseSalary'. It also has a method 'calculateSalary()'
that can be overridden by subclasses.

2️⃣Subclass Manager
Inherits from Employee, adds a 'bonus', and overrides 'calculateSalary()' to include bonus
amount.
3️⃣Subclass Developer
Inherits from Employee, adds 'projectAllowance', and overrides 'calculateSalary()'
accordingly.

4️⃣Main Class
Creates objects of Manager and Developer using Employee reference. Demonstrates
runtime polymorphism where the overridden method runs based on the actual object type.

Program Output
Raj's Salary: 60000.0
Priya's Salary: 48000.0

Key Concepts Demonstrated


Concept Explanation

Inheritance Manager and Developer inherit from


Employee.

Method Overriding Each subclass provides its own version of


calculateSalary().

Polymorphism Same method name shows different


behavior depending on the object.

Constructor Chaining super() is used to call the parent


constructor.

Code Reuse Common fields and methods are defined


once in superclass.

Excellent question, Rajitha 👏 — these are core OOP concepts and your students will
understand polymorphism and overriding better if you connect them with examples.
Let’s go step by step in simple words 👇

🧠 1. What is Polymorphism?

The word Polymorphism means “many forms”.


In Java, one method name can perform different actions depending on the object or
the context.

Example idea:
👉 The method name calculateSalary() is same in all classes,
but it behaves differently for Manager and Developer.
⚙️2. Types of Polymorphism in Java

When it
Type How it works Example
happens

Compile-time During Method Same method name, different


Polymorphism compilation Overloading parameter list

Same method name, same


Runtime During program Method
parameters, but in different classes
Polymorphism execution Overriding
(parent–child)

🔹 Compile-time Polymorphism (Method Overloading)

 Happens when multiple methods in the same class have the same name but
different parameters (type, number, or order).

 The compiler decides which version to run based on arguments passed.

Example:

class MathOperation {

int add(int a, int b) { // Method 1

return a + b;

double add(double a, double b) { // Method 2 (different type)

return a + b;

public class Main {

public static void main(String[] args) {

MathOperation m = new MathOperation();

[Link]([Link](5, 10)); // Calls int version


[Link]([Link](2.5, 3.5)); // Calls double version

🧩 Explanation:

 Both methods have the same name add(), but different parameter types.

 The compiler selects the correct one during compilation.


👉 That’s why it’s called compile-time polymorphism.

🔹 Runtime Polymorphism (Method Overriding)

 Happens when a subclass provides a new version of a method that already exists
in its superclass.

 Which version to use is decided at runtime, depending on the actual object type.

Example:

class Employee {

void work() {

[Link]("Employee is working");

class Developer extends Employee {

@Override

void work() {

[Link]("Developer is coding");

public class Main {


public static void main(String[] args) {

Employee e = new Developer(); // Reference of parent, object of child

[Link](); // Calls Developer's version (runtime decision)

🧩 Explanation:

 Even though the reference is of type Employee,


the object is of type Developer,
so Developer’s version runs.
👉 That’s why it’s runtime polymorphism.

3. What is a Constructor?

A constructor is a special method used to initialize objects when they are created.

Key Points:

 Has the same name as the class.

 No return type (not even void).

 Called automatically when an object is created using new.

 Can be overloaded (multiple constructors with different parameters).

Example:

class Employee {

String name;

double salary;

// Constructor

Employee(String n, double s) {

name = n;

salary = s;
}

public class Main {

public static void main(String[] args) {

Employee e = new Employee("Raj", 50000); // Constructor called automatically

[Link]([Link] + " earns " + [Link]);

🔁 4. What is Method Overriding?

 Happens when a child class defines a method with the same name, return type,
and parameters as a method in its parent class.

 The child’s version replaces (or overrides) the parent’s version.

 It’s used to change the behavior of a method for a specific subclass.

 @Override annotation helps the compiler ensure correctness.

Example:

class Animal {

void sound() {

[Link]("Animal makes a sound");

class Dog extends Animal {

@Override

void sound() {

[Link]("Dog barks");
}

public class Main {

public static void main(String[] args) {

Animal a = new Dog(); // Parent reference, child object

[Link](); // Dog's version runs (runtime polymorphism)

🧩 Explanation:

 sound() method is overridden in Dog.

 Output will be: Dog barks.

🧾 Summary Table

Concept Description Example

Special method used to initialize an


Constructor Employee(String name)
object

Same method name, different


Method add(int, int) and add(double,
parameters (Compile-time
Overloading double)
polymorphism)

Same method name and parameters in


calculateSalary() in Employee
Method Overriding parent and child classes (Runtime
and Manager
polymorphism)

Employee e = new
Runtime Actual method call decided during
Manager();
Polymorphism execution
[Link]();

Compile-time
Method call decided during compilation add(5, 10) vs add(5.5, 6.5)
Polymorphism
Would you like me to put all these explanations (with examples and table) into a Word
document like before for your students?

Method overriding in Java occurs when a subclass provides its own specific implementation
for a method that is already defined in its superclass. This allows for polymorphism, where
a single method call can result in different behaviors depending on the actual object type at
runtime.

Here's a breakdown of the key aspects:

 Inheritance:

Overriding is a concept tied to inheritance. A subclass inherits methods from its superclass.

 Same Signature:
The overriding method in the subclass must have the exact same method signature as the
method in the superclass. This includes:

 Same method name.

 Same number and types of parameters in the same order.

 Same return type (or a covariant return type, which means a subtype of the
original return type).

 Accessibility:

The overriding method in the subclass cannot have a more restrictive access modifier than
the overridden method in the superclass (e.g., if the superclass method is public, the
subclass method cannot be private).

 @Override Annotation:

It is good practice to use the @Override annotation above the overriding method in the
subclass. This annotation helps the compiler detect if you have made a mistake in the
method signature, preventing potential errors.

 Runtime Polymorphism:

When an overridden method is called through a reference variable of the superclass type,
the actual method executed is determined at runtime based on the actual object type, not
the reference type.

Example:

Java

class Animal {
public void makeSound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


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

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Animal();
[Link](); // Output: Animal makes a sound

Dog myDog = new Dog();


[Link](); // Output: Dog barks

Animal polymorphicAnimal = new Dog();


[Link](); // Output: Dog barks (runtime polymorphism)
}
}

In this example, the makeSound() method in Dog overrides the makeSound() method
in Animal. When [Link]() is called, even
though polymorphicAnimal is declared as an Animal type, it actually refers to a Dog object,
so the Dog's makeSound() method is executed.

No worries 😊 Rajitha — let’s go step-by-step in a very simple way.

🌸 What is Method Overriding?

Definition (in simple words):


When a subclass (child class) has a method with the same name, same parameters, and
same return type as a method in its parent class, then the child class overrides the
parent’s method.

It means — the child class gives its own version (or new definition) of the method.

💡 Think of it like this:

Your mother has a recipe for making tea ☕.


You also make tea, but you use your own method.
So, you override your mother’s tea-making method with your own version.

⚙️Programming Example

Let’s see it in Java 👇

// Parent class

class Animal {

void sound() {

[Link]("Animal makes a sound");

// Child class

class Dog extends Animal {

// Method overriding

void sound() {

[Link]("Dog barks");

// Main class
public class Main {

public static void main(String[] args) {

Animal myAnimal = new Animal(); // Object of parent class

[Link](); // Output: Animal makes a sound

Dog myDog = new Dog(); // Object of child class

[Link](); // Output: Dog barks

// Polymorphism example:

Animal obj = new Dog(); // Parent reference, child object

[Link](); // Output: Dog barks (method overridden)

🧠 Explanation

Part Meaning

Animal Parent class

Dog Child class

void sound() Method present in both classes

Dog’s version of sound() Overrides Animal’s version

Animal obj = new Dog(); [Link](); Java calls child’s version → runtime polymorphism

⚖️Key Points

1. Same method name in both parent and child.

2. Same parameters (same number and type).

3. Happens during runtime — so it’s called runtime polymorphism.


4. Used for giving specific behavior in the child class.

You might also like