runtime polymorphism in java :: futureX |
UPCASTING :
When reference variable of Parent class refers to the object of Child class, it is known as upcasting.
upcasing in java :: futureX |
void eat(){System.out.println("eating food");}
}
class Human extends Animal{
void eat(){System.out.println("eating delicious food");}
public static void main(String args[]){
Animal A=new Human();
A.eat();
}
}
Example of runtime polymorphism
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splender();//upcasting
b.run();
}
}
In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime. Since it is determined by the compiler, which method will be invoked at runtime, so it is known as runtime polymorphism.
Rule: Runtime polymorphism can't be achieved by data members.
class Bike{ int speedlimit=90; } class Honda extends Bike{ int speedlimit=150; public static void main(String args[]){ Bike obj=new Honda(); System.out.println(obj.speedlimit);//output 90 } }
JAVA TUTORIALS HOMEPAGE
No comments:
Post a Comment