#
Polymorphism in Java
In this tutorial I will present the concept of Java Polymorphism.
#
Polymorphism in Java - theory
In Java OPP (Object-Oriented Programming) we speak about 4 main concepts:
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
Polymorphism is the ability of an object to take on many forms.
In Java polymorphism is done using method overriding
and method overloading
.
Polymorphism allows you to define one interface and have multiple implementations, or you can extend and override a class.
Info
- method
overloading
-> Compile-time Polymorphism, also known as static polymorphism - method
overriding
-> Run-time Polymorphism, also known as dynamic polymorphism
#
Polymorphism in Java - example
Here is an example of Java polymorphism:
public class Shape {
public void drawShape1(){
System.out.println("Hello from drawShape1 !");
};
public void drawShape2(){
System.out.println("Hello from drawShape2 !");
};
}
public class Triangle extends Shape {
void eraseShape() {
System.out.println("Hello from Triangle/eraseShape !");
}
// method OVERRIDING
@Override
public void drawShape2() {
System.out.println("Hello from Triangle/eraseShape2 !");
}
// method OVERLOADING
public void drawShape2(String par1) {
System.out.println("Hello "+par1+" from eraseShape2 !");
}
}
Info
When a class inherits the methods of another class it can override
& overload
these methods.
public class MainApp {
public static void main(String [] args) {
Triangle triangle = new Triangle();
triangle.drawShape2();
triangle.drawShape2("Paris");
}
}
Info
As you can see in the Triangle class you can use drawShape2() method defined in the Shape class.
The method in Triangle class has different implementation as the one from the Shape class: this is overriding
.
We can add also another method with the same name, but with another signature: this is overloading
.