Welcome to our Java Polymorphism tutorial! Today, we're going to explore one of the most powerful features in Java - Polymorphism. Let's dive right in! 🐳
Polymorphism is a concept in object-oriented programming that allows one interface to be used for a general class of actions. In simpler terms, it enables objects of different classes to be treated as objects of a common superclass. Let's break that down!
Before we dive into Polymorphism, let's quickly review classes and objects.
For example, Car is a class, and Toyota and Honda are objects (or instances) of the Car class.
Let's consider a real-world example to understand Polymorphism better. Imagine a zoo with different types of animals. All animals can be fed, but each animal has a specific type of food. Instead of creating separate methods for each animal, we can create a general feed method in the Animal class and let each subclass (like Lion, Tiger, Elephant, etc.) handle the specifics. This is an example of Polymorphism!
class Animal {
void feed() {
// General feeding behavior
}
}
class Lion extends Animal {
void feed() {
// Specific feeding behavior for Lion
}
}
class Tiger extends Animal {
void feed() {
// Specific feeding behavior for Tiger
}
}Java supports two types of Polymorphism:
Compile-time Polymorphism (Method Overloading and Method Overriding)
Run-time Polymorphism (Function Overloading is NOT run-time polymorphism, it's Method Overloading)
Run-time Polymorphism is achieved using Interfaces and Abstract Classes. We won't cover Interfaces today, but we will discuss Abstract Classes!
An Abstract Class is a class that cannot be instantiated, but it can contain abstract methods. An abstract method is a method without a body, which is declared using the abstract keyword. Abstract classes are used to provide a generalized structure to a hierarchy of classes.
Here's an example of an abstract class:
abstract class Animal {
String name;
Animal(String name) {
this.name = name;
}
abstract void sound();
void displayName() {
System.out.println("The animal's name is: " + name);
}
}
class Lion extends Animal {
Lion() {
super("Lion");
}
void sound() {
System.out.println("The Lion says: Roar");
}
}
class Tiger extends Animal {
Tiger() {
super("Tiger");
}
void sound() {
System.out.println("The Tiger says: Growl");
}
}Now, let's see how we can use these classes:
public class Main {
public static void main(String[] args) {
Animal lion = new Lion();
Animal tiger = new Tiger();
lion.sound();
tiger.sound();
lion.displayName();
tiger.displayName();
}
}This code will output:
The Lion says: Roar
The Tiger says: Growl
The animal's name is: Lion
The animal's name is: Tiger
🎉 Congratulations! You've learned about Polymorphism in Java. Let's test your knowledge with a quiz:
What is the purpose of an Abstract Class in Java?
Remember, Polymorphism is a powerful feature in Java, and once mastered, it can make your code more flexible and easier to maintain. Keep practicing, and happy coding! 🚀