Home | Dynamic Method Dispatch or Runtime Polymorphism

Chapter: Web or internet Programming : JAVA

Dynamic Method Dispatch or Runtime Polymorphism

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism.

 

Dynamic Method Dispatch or Runtime Polymorphism:

 

 

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism.

 

A superclass reference variable can refer to a subclass object.

 

 

Java uses this fact to resolve calls to overridden methods at run time. When an overridden method is called through a superclass reference, Java determines which version of that method to execute based upon the type of the object being referred to at the time the call occurs. Thus, this determination is made at run time. When different types of objects are referred to, different versions of an overridden method will be called.

 

//method overriding class shape{

 

double dimension1; shape(double a){

 

dimension1=a;

 

}

double volume(){

 

System.out.println("volume for the shape is not defined"); return 0;

 

}

}

 

class sphere extends shape{ sphere(double a){

 

super(a);

}

 

double volume(){

 

System.out.println("in the computation of volume of sphere"); return (4/3)*Math.PI*Math.pow(dimension1, 3);

 

}

}

 

class hemisphere extends shape{ hemisphere(double a ){

 

super(a);

}

 

double volume(){

 

System.out.println("in the computation of volume of hemisphere"); return (2.0/3.0)*Math.PI*Math.pow(dimension1, 3);

 

}

}

 

public class overrideclas {

 

public static void main(String args[]){ shape f = new shape(2);

 

sphere s=new sphere(3); hemisphere hs=new hemisphere(4);

 

shape ref;

 

ref=s;

 

System.out.println("the volume is "+ ref.volume());

 

ref=hs;

 

System.out.println("the volume is "+ ref.volume());

 

ref=f;

 

System.out.println("the volume is "+ ref.volume());

}

 

}

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Web or internet Programming : JAVA : Dynamic Method Dispatch or Runtime Polymorphism |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.