Professional Documents
Culture Documents
Polymorphism
Polymorphism
Polymorphism
Polymorphism
SIT Internal
Learning outcomes
➢ What is polymorphism?
➢ Types of polymorphism
❑ Method Overloading
❑ Method Overriding
SIT Internal
Poly morphism
many form
SIT Internal
What is Polymorphism
What is Polymorphism?
Dog Woof
Speak
Cat ?
SIT Internal
Polymorphism
Method Overloading
Allows class to have more than one method having the same name, if their
argument lists are different.
Method Overloading
class Calculator {
public int add(int a, int b) {
return a + b;
Calculator calculator = new Calculator();
}
int sum1 = calculator.add(5, 10);
public int add(int a, int b, int c) int sum2 = calculator.add(1, 2, 3);
{
return a + b + c;
}
}
SIT Internal
class Vehicle {
private String make;
private String model;
private int year; class Main {
public static void main(String[] args) {
public Vehicle(String m, String mod, int year) { Vehicle vehicle1 = new Vehicle("Toyota", "Camry“,
make = m;
model = mod; 2020);
year = y; Vehicle vehicle2 = new Vehicle("Honda", "Civic");
}
}
public Vehicle(String m, String mod) {
}
make = m;
model = mod;
}
}
SIT Internal
Method Overriding
subclass overrides the method inherited from the superclass and
provides its specific implementation.
Code Example
class Animal {
public void speak() {
System.out.println("Animal makes a sound"); class Main {
} public static void main(String[] args) {
} Animal animalDog = new Dog();
class Dog extends Animal { Animal animalCat = new Cat();
public void speak() { animalDog.speak();
System.out.println("Dog barks");
animalCat.speak();
}
}
}
class Cat extends Animal { }
public void speak() {
System.out.println("Cat meows");
}
}
SIT Internal
Method Overriding
subclass overrides the method inherited from the superclass and
provides its specific implementation.
Code Example
class Animal {
protected void speak() {
System.out.println("Animal makes a sound"); class Main {
} public static void main(String[]
} args) {
Animal animal = new Dog();
class Dog extends Animal { animal.speak();
public void speak() { }
System.out.println("Dog barks"); }
}
}
SIT Internal
Code Example
class Animal {
protected void speak() {
System.out.println("Animal makes a sound"); class Main {
} public static void main(String[]
} args) {
Animal animal = new Dog();
class Dog extends Animal { animal.speak();
private void speak() { }
System.out.println("Dog barks"); }
}
}
SIT Internal
Summary
• Polymorphism: actual type of an object can be different from the type it
is declared as.
• Method overloading deals with multiple methods with the same name in
the same class, but with different signatures
• Method overriding deals with two methods, one in a parent class and
one in a child class, that have the same signature