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

Java Polymorphism

Uploaded by

pherjanes0215
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
6 views5 pages

Java Polymorphism

Uploaded by

pherjanes0215
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 5

Java

Polymorphis
m
Polymorphism means "many forms", and it occurs when we have
many classes that are related to each other by inheritance.
Like we specified in the previous chapter; Inheritance lets us
inherit attributes and methods from another class.

Polymorphism uses those methods to perform different tasks.


This allows us to perform a single action in different ways.
For example, think of a superclass called Animal that has a
method called animalSound(). Subclasses of Animals could be
Pigs, Cats, Dogs, Birds - And they also have their own
implementation of an animal sound (the pig oinks, and the cat
meows, etc.):
} ..
Example

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

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee wee"); Remember
}
from
}
the Inheritan
class Dog extends Animal { ce
public void animalSound() { Chapter that
System.out.println("The dog says: bow wow");
}
}
we use
}
the extends
keyword to
inherit from
Class Main {
Now we can create Pig and Dog objects and
public call void main(String[] args) {
static
Animal myAnimal = new Animal(); // Create a
the animalSound() method on both of them:
Animal object
Animal myPig = new Pig(); // Create a Pig
class Animal { object
public void animalSound() { Animal myDog = new Dog(); // Create a Dog
System.out.println("The animal makes a sound"); object
} myAnimal.animalSound();
} myPig.animalSound();
myDog.animalSound();
class Pig extends Animal { }
public void animalSound() { }
System.out.println("The pig says: wee wee");
}
} Now we can create Pig and Dog objects and call
the animalSound() method on both of them:
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
Why And When To Use
"Inheritance" and
"Polymorphism"?
- It is useful for code
reusability: reuse attributes
and methods of an existing
class when you create a new
class.

You might also like