Exercise-8
a)Runtime Polymorphism
SOURCE-CODE:
AIM: To write a JAVA program that implements Runtime polymorphism
class A
{
void display()
{
System.out.println("Inside A class");
}
}
class B extends A
{
void display()
{
System.out.println("Inside B class");
}
}
class C extends A
{
void display()
{
System.out.println("Inside C class");
}
}
class runtimedemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
A ref;
ref=c1;
ref.display();
ref=b1;
ref.display();
ref=a1;
ref.display();
}
}
OUT-PUT:
Inside C class
Inside B class
Inside A class
b)Case study on Runtime Polymorphism
AIM: To write a Case study on run time polymorphism, inheritance that implements in
above problem
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
When an overridden method is called through a superclass reference, Java determines
which version(superclass/subclasses) of that method is to be executed based upon the
type of the object being referred to at the time the call occurs. Thus, this
determination is made at run time.
At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.
Upcasting
Therefore, if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable,
different versions of the method are executed. Here is an example that illustrates
dynamic method dispatch:
The example is given by
Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate
of interest may differ according to banks. For example, SBI, ICICI and AXIS banks
are providing 8.4%, 7.3% and 9.7% rate of interest


Comments
Post a Comment