Upcasting:
When reference variable of Parent class refers to the object of Child class, it is known as upcasting.
For example:
class A{} class B extends A{}
class Test{ public static void main(String args[]){ A a=new B();//upcasting } }
Example of Runtime Polymorphism:
In this example, we are creating two classes Bicycle and HondaShine. HondaShine class extends Bicycle 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.
class Bicycle{ void run(){ System.out.println("bicycle is running"); } } class HondaShine extends Bicycle{ void run(){ System.out.println("shine is running safely with 70km"); } public static void main(String args[]){ Bicycle b = new HondaShine();//upcasting b.run(); } }
Runtime Polymorphism with data member:
Method is overriden not the datamembers, so runtime polymorphism can’t be achieved by data members.
In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.
class Bicycle{ int speedlimit=100; } class HondaShine extends Bicycle{ int speedlimit=160; public static void main(String args[]){ Bicycle obj=new HondaShine(); System.out.println(obj.speedlimit); } }
Note: Runtime polymorphism can’t be achieved by data members.
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…