0% found this document useful (0 votes)
5 views

Polymorphism and Inheritance

The document explains key concepts of polymorphism and inheritance in Object-Oriented Programming (OOP), focusing on Java. It details compile-time polymorphism through method overloading and runtime polymorphism through method overriding, providing code examples for each. Additionally, it discusses inheritance types, including single, multilevel, and hierarchical inheritance, and explains how Java implements multiple inheritance using interfaces.

Uploaded by

kvkumaravel28
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Polymorphism and Inheritance

The document explains key concepts of polymorphism and inheritance in Object-Oriented Programming (OOP), focusing on Java. It details compile-time polymorphism through method overloading and runtime polymorphism through method overriding, providing code examples for each. Additionally, it discusses inheritance types, including single, multilevel, and hierarchical inheritance, and explains how Java implements multiple inheritance using interfaces.

Uploaded by

kvkumaravel28
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Polymorphism ,Inheritance

• Polymorphism is one of the four core principles of Object-Oriented


Programming (OOP), alongside inheritance, encapsulation, and
abstraction. It allows objects of different classes to be treated as
objects of a common superclass. The main idea is that the same
method can behave differently based on the object it is acting upon.
• In Java, polymorphism is mainly divided into two types:
1.Compile-time Polymorphism (Method Overloading)
2.Runtime Polymorphism (Method Overriding)
Compile-time Polymorphism (Method Overloading)

• This occurs when multiple methods have the same name but differ in
the number or type of their parameters. The correct method is chosen at
compile time based on the method signature.
class Calculator {
// Method to add two integers
public int add(int a, int b) {
return a + b; }
// Overloaded method to add three integers
public int add(int a, int b, int c) {
return a + b + c; }
// Overloaded method to add two doubles
public double add(double a, double b)
{
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum of 10 and 20: " + calc.add(10, 20)); // Calls the first method
System.out.println("Sum of 10, 20, and 30: " + calc.add(10, 20, 30)); // Calls the second method
System.out.println("Sum of 10.5 and 20.5: " + calc.add(10.5, 20.5)); // Calls the third method
}
Code explanantion
• Class Calculator

• This class has three overloaded methods named add. Method overloading allows the same method name to be used, but
with different parameters (number or type). This is a feature of compile-time polymorphism.

• public int add(int a, int b)

• This method takes two integers as parameters and returns their sum. The return type is int (an integer).

public int add(int a, int b) {

return a + b;

• public int add(int a, int b, int c)

• This method is overloaded. It takes three integers as parameters and returns their sum. It has the same method name,
but the parameters are different from the first one (this one has an extra integer).

• public double add(double a, double b)

• This method is also overloaded but it takes two double values as parameters and returns their sum as a double. This
method is different because it uses double type parameters and return type.
• Class Main

• The Main class contains the main method, where the program begins its execution.

public class Main {

public static void main(String[] args) {

Calculator calc = new Calculator();

 A new instance of the Calculator class is created and assigned to the variable calc.

• Calling calc.add(10, 20)

• This calls the method add that takes two integers as parameters. The method signature is public int add(int a, int
b), so it adds 10 and 20, resulting in 30.

• System.out.println("Sum of 10 and 20: " + calc.add(10, 20));

• Output: Sum of 10 and 20: 30


• Calling calc.add(10, 20, 30)

• This calls the method add that takes three integers as parameters. The method signature is public int add(int a, int
b, int c), so it adds 10 + 20 + 30, resulting in 60.

• Output: Sum of 10, 20, and 30: 60

• Calling calc.add(10.5, 20.5)

• This calls the method add that takes two doubles as parameters. The method signature is public double
add(double a, double b), so it adds 10.5 + 20.5, resulting in 31.0.

• Output: Sum of 10.5 and 20.5: 31.0


during the method calls
 Method Overloading: Java determines which method to call based on the method signature, i.e., the number and type of arguments.

o add(10, 20) matches the first method (int add(int a, int b)).

o add(10, 20, 30) matches the second method (int add(int a, int b, int c)).

o add(10.5, 20.5) matches the third method (double add(double a, double b)).

• Final Output:

• Sum of 10 and 20: 30

• Sum of 10, 20, and 30: 60

• Sum of 10.5 and 20.5: 31.0

• Conclusion:

 The program demonstrates method overloading where the method add is defined multiple times with different
parameter lists, and the appropriate method is called based on the arguments passed.

 Compile-time polymorphism occurs here, meaning the method that gets executed is determined at compile time
based on the method signature.
Runtime Polymorphism (Method Overriding)
• Runtime polymorphism occurs when a subclass provides a specific
implementation of a method that is already defined in its superclass. This
is known as method overriding. In this case, the method that gets
executed is determined at runtime based on the object type.
class Animal {
// Method in the superclass
public void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


// Overriding method in the subclass
• @Override
public void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


// Overriding method in the subclass
@Override
public void sound() {
System.out.println("Cat meows");
}
public class Main {
public static void main(String[] args) {
// Polymorphism in action
Animal animal1 = new Dog();
Animal animal2 = new Cat();

// Calls the overridden method based on the object type


animal1.sound(); // Outputs: Dog barks
animal2.sound(); // Outputs: Cat meows
}
}
• Class Animal (Superclass)
• The class Animal has a method sound() which prints a generic message: "Animal makes a sound". This is a general
definition that all subclasses of Animal can inherit, but they can also override this method to provide their own
implementation.

• Class Dog (Subclass of Animal)


• The Dog class extends the Animal class, meaning it inherits the sound() method.

• However, the Dog class overrides the sound() method with its own version, which prints "Dog barks" instead of
the default message from Animal.

• Class Cat (Subclass of Animal)


• The Cat class also extends Animal and overrides the sound() method to print "Cat meows".
Class Main
• Key Points in the Main Class:

1. Polymorphism:
o In the main method, we are demonstrating runtime polymorphism.

o The variables animal1 and animal2 are references of type Animal, but they are pointing to objects of type Dog
and Cat respectively.

2. Dynamic Method Dispatch:


o Even though both animal1 and animal2 are of type Animal, the method that gets called is determined at
runtime based on the actual object type (either Dog or Cat).
o This is an example of method overriding, where a subclass provides its specific implementation of a method
that is already defined in the superclass.

3. Method Calls:
o animal1.sound();: Since animal1 is referencing a Dog object, the overridden sound() method in the Dog class
is executed, which prints "Dog barks".
o animal2.sound();: Similarly, since animal2 is referencing a Cat object, the overridden sound() method in the
Cat class is executed, which prints "Cat meows".
Explanation of Runtime Polymorphism:
 At compile time, Java knows that both animal1 and animal2 are references of type Animal.

 However, at runtime, it sees that animal1 actually points to an object of type Dog and animal2 points to an object of
type Cat.

 Based on the actual object types, Java calls the overridden methods in the Dog and Cat classes, not the one in the
Animal class.

• This is runtime polymorphism because the method that is invoked (sound()) is decided during execution based on the
type of the object (Dog or Cat), not the reference type (Animal).
Conclusion

• Method Overriding allows subclasses to provide specific


implementations of methods defined in the superclass.
• Runtime Polymorphism occurs because the method call is resolved at
runtime based on the actual object type, not the reference type.
• This is a great way to make your code more flexible and extensible, as
you can have different behaviors (methods) for objects of different
types while using the same reference type.
• Inheritance is one of the core principles of Object-Oriented Programming (OOP) and allows a class to inherit
properties and methods from another class. In Java, inheritance helps achieve code reusability, as a subclass
can reuse fields and methods from its superclass, and it can also add new fields and methods or override
inherited methods.

• Key Concepts of Inheritance in Java:

1. Superclass (Parent Class): The class whose properties and methods are inherited by another class.

2. Subclass (Child Class): The class that inherits the properties and methods from the superclass.

3. extends Keyword: In Java, inheritance is established using the extends keyword.


Types of Inheritance
• Single Inheritance: One class inherits from another (i.e., one subclass and
one superclass).
• Multilevel Inheritance: A class inherits from a subclass, forming a chain of
inheritance.
• Hierarchical Inheritance: Multiple subclasses inherit from a single
superclass.
• Multiple Inheritance (via interfaces): Java doesn't support multiple
inheritance directly for classes, but you can achieve multiple inheritance
through interfaces.
// Superclass (Parent Class)
class Animal {
// Fields
String name;

// Constructor
public Animal(String name) {
this.name = name;
}

// Method in the superclass


public void sound() { System.out.println("Animal makes a sound");
}

// Method to display the name


public void display() {
System.out.println("Animal's name is: " + name);
}
}

// Subclass (Child Class)


class Dog extends Animal {
// Constructor of subclass
public Dog(String name) {
// Calling superclass constructor
super(name);
// Overriding the sound method from the Animal class
@Override
public void sound() {
System.out.println("Dog barks");
}
}

// Main class to test inheritance


public class Main {
public static void main(String[] args) {
// Creating an object of the subclass (Dog)
Dog dog = new Dog("Buddy");

// Calling the inherited method display() from Animal class


dog.display(); // Outputs: Animal's name is: Buddy

// Calling the overridden method sound() from Dog class


dog.sound(); // Outputs: Dog barks
}
Explanation
• Superclass (Animal):

 It has a field name, a constructor to initialize name, and two methods: sound() (which prints a generic sound)
and display() (which prints the name of the animal).

•  Subclass (Dog):

 The Dog class inherits from the Animal class. It uses the super keyword to call the superclass constructor,
initializing the name.

 The Dog class overrides the sound() method from the Animal class to give a specific implementation (i.e.,
printing "Dog barks").

• In the Main class:

 A Dog object is created and assigned to the variable dog.

 dog.display() is called, which is inherited from Animal, and it prints the name of the animal.

 dog.sound() is called, which calls the overridden sound() method from Dog and prints "Dog barks".
// Superclass
Example of Multilevel Inheritance

class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}
}
// Subclass
class Dog extends Animal {
public void sound() {
System.out.println("Dog barks");
}
}

// Subclass of Dog (Multilevel inheritance)


class Puppy extends Dog {
public void sound() {
System.out.println("Puppy squeaks");
}
}

public class Main {


public static void main(String[] args) {
Puppy puppy = new Puppy();
puppy.sound(); // Outputs: Puppy squeaks
}
• output

• Puppy squeaks

• In this case, Puppy is a subclass of Dog, and Dog is a subclass of Animal. This is an example of multilevel
inheritance.

• Conclusion:

 Inheritance helps create a hierarchy between classes, allowing for code reuse, extensibility, and better
organization of classes.

 Java supports single, multilevel, and hierarchical inheritance, and provides the super keyword for accessing
superclass members.

 It's important to remember that constructors are not inherited, but methods can be inherited or overridden
by subclasses.
Multiple inheritance

• In Java, multiple inheritance refers to a scenario where a class can inherit


features (fields and methods) from more than one class. However, Java does
not support multiple inheritance directly with classes to avoid ambiguity Java
achieves multiple inheritance through interfaces.
• Real-World Scenario for Multiple Inheritance in Java:
• Let's consider a real-world scenario involving MultiFunctionalDevice (MFD)
that acts as both a Printer and a Scanner.
• Printer: A device that can print documents.
• Scanner: A device that can scan documents.
• MultiFunctionalDevice (MFD): A device that can perform both printing and
scanning operations.
• To Create a program that models different shapes and demonstrates
polymorphism in Java.
• To create a basic program using multiple inheritance.

You might also like