Polymorph Is M
Polymorph Is M
Introduction
class ShapesMain {
public static void main(String[] args) {
Shape[] shapes = { new Circle(10, 20, 30),
new Rectangle(20, 30, 40, 50) };
for (int i = 0; i < shapes.length; i++)
shapes[i].draw();
}
}
Types of Polymorphism in JAVA
Polymorphism
Method Method
Overloading Overriding
Method Overloading (Compile-time
Polymorphism or Static Polymorphism)
• Number of parameters.
class DisplayOverloading2{
public void disp(char c) {
System.out.println(c);
}
public void disp(int c) {
System.out.println(c);
}
}
class Sample2{
public static void main(String args[]) {
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5); Output:
} a
} 5
Method Overloading (Compile-time
Polymorphism or Static Polymorphism)
Example3: Overloading – Sequence of data type of arguments
Here method disp() is overloaded based on sequence of data type of arguments
class DisplayOverloading3 {
public void disp(char c, int num) {
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c) {
System.out.println("I’m the second definition of method disp" );
}
}
class Sample3{
public static void main(String args[]) {
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
Output:
}
I’m the first definition of method disp
} I’m the second definition of method disp
Lets see few Valid/invalid cases of method
overloading
Case 1:
int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)
Result: Compile time error. Argument lists are exactly same. Both methods are having
same number, data types and same sequence of data types in arguments.
Case 2:
int mymethod(int a, int b)
int mymethod(float var1, float var2)
Result: Perfectly fine. Valid case for overloading. Here data types of arguments are
different.
Case 3:
int mymethod(int a, int b)
int mymethod(int num)
Result: Perfectly fine. Valid case for overloading. Here number of arguments are
different.
Lets see few Valid/invalid cases of method
overloading
Case 4:
Result: Perfectly fine. Valid case for overloading. Sequence of the data types are
different, first method is having (int, float) and second is having (float, int).
Case 5:
Result: Compile time error. Argument lists are exactly same. Even though return type of
methods are different, it is not a valid case. Since return type of method doesn’t matter
while overloading a method.
Rules for Method Overloading