Java Polymorphism
Polymorphism is a fundamental concept in Object-Oriented Programming (OOP) and is a feature of Java. It is the ability of an object to take on multiple forms. In Java, polymorphism is achieved through method overriding and method overloading.
Method Overloading
Method overloading is when a class has multiple methods with the same name but different parameters. The compiler will determine which method to call based on the number and type of parameters passed to the method. Here's an example of method overloading in Java:
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
Method Overriding
Method overriding is when a subclass provides a new implementation of a method that is already defined in its superclass. The new implementation "overrides" the old one.
Method overriding is an important aspect of polymorphism and is used to achieve dynamic polymorphism in Java. Here's an example of method overriding in Java:
class Shape {
void draw() {
System.out.println("Drawing a Shape");
}
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a Circle");
}
}
class Square extends Shape {
void draw() {
System.out.println("Drawing a Square");
}
}
In the above example, the Shape
class has a draw()
method, which is overridden in the Circle
and Square
classes. If we create an instance of each class and call the draw()
method on each instance, we'll get different results, demonstrating polymorphism in action.
Shape shape = new Shape();
shape.draw(); // Drawing a Shape
Shape circle = new Circle();
circle.draw(); // Drawing a Circle
Shape square = new Square();
square.draw(); // Drawing a Square
In conclusion, polymorphism is a powerful feature of Java that allows objects to take on multiple forms and enables dynamic behavior at runtime.