Part 8: Java Polymorphism with its real time example code.

JAVA

Java Polymorphism

Polymorphism means “many forms”, It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class. It occurs when we have many classes that are related to each other by inheritance. Like we definite 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 diverse ways.

For example, think of a superclass called Tree that has a method called treeSound(). Subclasses of Tree could be SmallTree, MidSizeTree.  And they also have their own implementation of an tree sound:

Example
class Tree {
public void treeSound() {
System.out.println(“The tree makes a sound in wind”);
}
}
class SmallTree extends Tree {
public void treeSound() {
System.out.println(“The SmallTree can also makes a sound in wind”);
}
}
class MidSizeTree extends c {
public void treeSound() {
System.out.println(“The MidSizeTree can also makes a sound in wind”);
}
}

Remember from the Inheritance chapter that we use the extends keyword to inherit from a class.Now we can create Pig and Dog objects and call the animalSound() method on both of them:

Example
class Tree {
public void treeSound() {
System.out.println(“The tree makes a sound in wind”);
}
}
class SmallTree extends Tree {
public void treeSound() {
System.out.println(“The SmallTree can also makes a sound in wind”);
}
}

class MidSizeTree extends c {
public void treeSound() {
System.out.println(“The MidSizeTree can also makes a sound in wind”);
}
}
class Main {
public static void main(String[] args) {
Tree myTree = new Tree(); // create Tree obj
Tree mySmall = new SmallTree();// create SmallTree obj
Tree myMidSize = new MidSizeTree();// create MidSizeTree obj
myTree.treeSound();
mySmall.treeSound();
mymyMidSize.treeSound();
}
}

OUTPUT

The tree makes a sound in wind
The SmallTree makes a sound in wind
The MidSizeTree can also makes a sound in wind

0 Comments

You may find interest following article

Complete Guide: Create Laravel Project in Docker Without Local Dependencies

Create Laravel Project Through Docker — No Need to Install PHP, MySQL, or Apache on Your Local Machine In this tutorial, I’ll show you how to create and run a full Laravel project using Docker containers. That means you won’t have to install PHP, MySQL, or Apache locally on your computer. By the end of this guide, you’ll have a fully functional Laravel development...