Run-time polymorphism is the ability of an object to play multiple roles at run-time. See the following program where the object of Cal class will have different behaviors according the reference variable through which it is pointed. If we access Cal object using c, it has add() and sub() methods. If we access it using a reference variable then only add() method is accessible and same is for b variable that allows to access only sub() method.
So in spite of having same object, It is playing different role according to the type of reference variable that is pointing it.
//Example of polymorphism
package poly;
interface Adder{
void add(int x,int y);
}
interface Substractor{
void sub(int x,int y);
}
class Cal implements Adder,Substractor{
@Override
public void add(int a,int b){
System.out.println(a+b);
}
@Override
public void sub(int s,int y){
System.out.println(s-y);
}
}
public class PolyMorphicViewOfAnObject {
public static void main(String[] args) {
Cal c=new Cal();
Adder a=c;
Substractor s=c;
s.sub(12,3);
a.add(23, 34);
c.add(23, 455);
c.sub(44, 5);
}
}
So in spite of having same object, It is playing different role according to the type of reference variable that is pointing it.
//Example of polymorphism
package poly;
interface Adder{
void add(int x,int y);
}
interface Substractor{
void sub(int x,int y);
}
class Cal implements Adder,Substractor{
@Override
public void add(int a,int b){
System.out.println(a+b);
}
@Override
public void sub(int s,int y){
System.out.println(s-y);
}
}
public class PolyMorphicViewOfAnObject {
public static void main(String[] args) {
Cal c=new Cal();
Adder a=c;
Substractor s=c;
s.sub(12,3);
a.add(23, 34);
c.add(23, 455);
c.sub(44, 5);
}
}
Comments