The Wayback Machine - https://web.archive.org/web/20241114072700/https://www.geeksforgeeks.org/dynamic-method-dispatch-runtime-polymorphism-java/
Open In App

Dynamic Method Dispatch or Runtime Polymorphism in Java

Last Updated : 09 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Overriding in java, Inheritance

Method overriding is one of the ways in which Java supports 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.

  • 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.
Blank Diagram - Page 1 (4)

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:

Java
// A Java program to illustrate Dynamic Method
// Dispatch using hierarchical inheritance
class A
{
    void m1()
    {
        System.out.println("Inside A's m1 method");
    }
}

class B extends A
{
    // overriding m1()
    void m1()
    {
        System.out.println("Inside B's m1 method");
    }
}

class C extends A
{
    // overriding m1()
    void m1()
    {
        System.out.println("Inside C's m1 method");
    }
}

// Driver class
class Dispatch
{
    public static void main(String args[])
    {
        // object of type A
        A a = new A();

        // object of type B
        B b = new B();

        // object of type C
        C c = new C();

        // obtain a reference of type A
        A ref;
        
        // ref refers to an A object
        ref = a;

        // calling A's version of m1()
        ref.m1();

        // now ref refers to a B object
        ref = b;

        // calling B's version of m1()
        ref.m1();

        // now ref refers to a C object
        ref = c;

        // calling C's version of m1()
        ref.m1();
    }
}

Output:

Inside A's m1 method
Inside B's m1 method
Inside C's m1 method

Explanation :

The above program creates one superclass called A and it’s two subclasses B and C. These subclasses overrides m1( ) method.

    1. Inside the main() method in Dispatch class, initially objects of type A, B, and C are declared.
      A a = new A(); // object of type A
      B b = new B(); // object of type B
      C c = new C(); // object of type C
      
      Blank Diagram - Page 1 (1)
    2. Now a reference of type A, called ref, is also declared, initially it will point to null.
      A ref; // obtain a reference of type A
      
      w
    3. Now we are assigning a reference to each type of object (either A’s or B’s or C’s) to ref, one-by-one, and uses that reference to invoke m1( ). As the output shows, the version of m1( ) executed is determined by the type of object being referred to at the time of the call.
      ref = a; // r refers to an A object
      ref.m1(); // calling A's version of m1()
      
      q
      ref = b; // now r refers to a B object
      ref.m1(); // calling B's version of m1()
      
      q
      ref = c; // now r refers to a C object
      ref.m1(); // calling C's version of m1()
      
      Blank Diagram - Page 1 (3)

Runtime Polymorphism with Data Members

In Java, we can override methods only, not the variables(data members), so runtime polymorphism cannot be achieved by data members.

For example :

Java
// Java program to illustrate the fact that
// runtime polymorphism cannot be achieved
// by data members

// class A
class A
{
    int x = 10;
}

// class B
class B extends A
{
    int x = 20;
}

// Driver class
public class Test
{
    public static void main(String args[])
    {
        A a = new B(); // object of type B

        // Data member of class A will be accessed
        System.out.println(a.x);
    }
}

Output:

10

Explanation :

In above program, both the class A(super class) and B(sub class) have a common variable ‘x’. Now we make object of class B, referred by ‘a’ which is of type of class A. Since variables are not overridden, so the statement “a.x” will always refer to data member of super class.

Advantages of Dynamic Method Dispatch

  1. Dynamic method dispatch allow Java to support overriding of methods which is central for run-time polymorphism.
  2. It allows a class to specify methods that will be common to all of its derivatives, while allowing subclasses to define the specific implementation of some or all of those methods.
  3. It also allow subclasses to add its specific methods subclasses to define the specific implementation of some.

Static vs Dynamic binding

  • Static binding is done during compile-time while dynamic binding is done during run-time.
  • private, final and static methods and variables uses static binding and bonded by compiler while overridden methods are bonded during runtime based upon type of runtime object


Previous Article
Next Article

Similar Reads

Java.lang.Runtime class in Java
In Java, the Runtime class is used to interact with Every Java application that has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime() method. Methods of Java Runtime classMethod Action PerformedaddShutdownHoo
6 min read
Java Runtime runFinalization() Method with Examples
In Java, every object has a method called finalize(). Before reclaiming the memory that the actual object was exploited, the garbage collector calls this method. It provides an opportunity for an object to perform cleanup operations earlier than it is garbage collected. However, the execution of finalize() is not secure, and it depends on when the
3 min read
Java Runtime exit() Method with Examples
Java Runtime exit() method is used to terminate currently running Java code in the Java virtual machine (JVM). This is an alternative way for System.exit(). Nevertheless, it is less commonly used than System.exit() because Runtime.getRuntime().exit() introduces an unnecessary object creation with a method or function calling. Likewise in System.exi
3 min read
Java Runtime totalMemory() Method with Examples
In Java, to access the system's properties and resources we have the Runtime class. The totalMemory() method is a method that the Runtime class gives you to get the total memory available in the JVM. To get the total memory in your Java Virtual Machine, use totalMemory() method which returns the total memory available. The totalMemory() returns bot
4 min read
Java Runtime freeMemory() Method with Examples
In Java, memory management plays a crucial role. It works on dynamic memory allocation and release. Java's Runtime class provides a number of ways to interact with the runtime environment, including memory-related operations. In this article, look into the freeMemory() in-built method provided by JDK, which tells you how much free memory the Java V
3 min read
Java Runtime exec() Method with Examples
The Runtime class's exec() method is your key to making your Java application interact with the operating system, if you've ever wanted it to. In this post, we'll examine the exec() method in great detail, dissect its fundamental ideas, and highlight all of its different applications. Java Runtime exec() MethodImagine you're running a Java program,
5 min read
Java Runtime getRuntime() Method with Examples
In Java, the Runtime class allows you to interact with the runtime environment of your application. One of the essential methods provided by this class is getRuntime(). This method returns the runtime object associated with the current Java application. With this object, you can access information about the runtime environment, execute system comma
2 min read
Java Runtime halt() Method with Examples
Java Runtime halt() Method is used to forcefully terminate the currently running Java code in Java Virtual Machine(JVM). Unlike System.exit(), this method is used in extreme situations where we need an immediate shutdown of the Java Virtual Machine(JVM). It does not invoke shutdown hooks and has a clean shutdown. It terminated the code immediately
4 min read
Java Runtime maxMemory() Method with Examples
In the Runtime class of Java, the maxMemory() Method returns the maximum memory designed for the Java Virtual Machine (JVM). In other words, we can say that it returns the maximum amount of memory JVM can use. This method returns a 'long' value representing the maximum amount of memory JVM can use. We can use the maxMemory() method to make runtime
4 min read
Java Runtime availableProcessors() Method with Examples
In the Runtime class of Java, there is a method availableProcess(). This method basically returns the number of processors available on the machine during runtime. It returns an integer value representing the number of processor cores used by Java Virtual Machine (JVM). This value is always 1 or greater than 1 because many modern-day computers have
3 min read
Java Runtime gc() Method with Examples
By recovering space from useless resources, garbage collection in Java streamlines the time-consuming operation of memory management. When memory becomes scarce, the JVM's garbage collection kicks off immediately. However, developers can utilize the gc() function to actively contact the JVM to perform the work. This method is part of the java.lang.
3 min read
Java Runtime load() Method
In Java Programming Langauge the Runtime class mainly allows us to interact with the runtime environment of our application. There is one of the important method load() provided by this Runtime class which allows Java applications to dynamically load the libraries into the Java environment. In this article, we will see the detailed overview, syntax
4 min read
Java Runtime traceInstructions() Method with Examples
The traceInstructions() method in the Java Runtime class provides the mechanism for the trace instructions executed by a Java program dynamically. It's a useful tool for debugging and performance analysis allowing the developers to monitor the sequence of the instructions executed during the runtime. Java Runtime traceInstructions() MethodThe trace
2 min read
Interfaces and Polymorphism in Java
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help
6 min read
Variables in Java Do Not Follow Polymorphism and Overriding
Variables in Java do not follow polymorphism. Overriding is only applicable to methods but not to variables. In Java, if the child and parent class both have a variable with the same name, Child class's variable hides the parent class's variable, even if their types are different. This concept is known as Variable Hiding. In the case of method over
2 min read
Output of Java program | Set 25 (Polymorphism)
Pre-requisite: Polymorphism in java 1) What is the output of the following program? class GFG { protected void getData() { System.out.println("Inside GFG"); } } class GeeksforGeeks extends GFG { protected void getData() { System.out.println("Inside GeeksforGeeks"); } } public class Test { public static void main(String[] args) {
3 min read
Compile Time Polymorphism in Java
Polymorphism in Java refers to an object's capacity to take several forms. Polymorphism allows us to perform the same action in multiple ways in Java. Polymorphism is divided into two types: Compile-time polymorphismRun time polymorphismNote: Run time polymorphism is implemented through Method overriding. Whereas Compile Time polymorphism is implem
7 min read
Difference between Compile-time and Run-time Polymorphism in Java
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. In this article, we will see the difference between two types of polymorphisms, compile time and run time. Compile Time Polymorphism: Whenever an object is bound with its functionality at the
3 min read
Polymorphism in Java
The word 'polymorphism' means 'having many forms'. In simple words, we can define Java Polymorphism as the ability of a message to be displayed in more than one form. In this article, we will learn what is polymorphism and its type. Real-life Illustration of Polymorphism in Java: A person can have different characteristics at the same time. Like a
6 min read
How is CompileTime classpath different from RunTime classpath in Java?
What is a Classpath? Classpath refers to the Path where all the classes/jars are available. What is Compile-time classpath? This classpath has all the classes/jars required to compile the application without any syntax error. Now we might think that our project compiled successfully so it will execute nicely. But this is not always true why because
2 min read
Runtime JAR File in Java
JAR stands for Java Archive file. It is a platform-independent file format that allows bundling and packaging all files associated with java application, class files, audio, and image files as well. These files are needed when we run an applet program. It bundles JAR files use a Data compression algorithm. These jar files can be manipulated using z
4 min read
Runtime Type Identification in Java
Runtime Type Identification in Java can be defined as determining the type of an object at runtime. It is extremely essential to determine the type for a method that accepts the parameter of type java.lang. Unlike C++ Java does not support Runtime Type Identification (RTTI) but it provides few methods to find objects at runtime. Some essential poin
2 min read
Calling an External Program in Java using Process and Runtime
Java contains the functionality of initiating an external process - an executable file or an existing application on the system, such as Google Chrome or the Media Player- by simple Java code. One way is to use following two classes for the purpose: Process class Runtime class The Process class present in the java.lang package contains many useful
2 min read
Understanding Encapsulation, Inheritance, Polymorphism, Abstraction in OOPs
As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of t
6 min read
CompileTime Vs RunTime Resolution of Strings
Compile-Time Resolution of Strings: When Strings are created with the help of String literals and '+' operator, they get concatenated at compile time. This is referred to as Compile-Time Resolution of Strings. Compiler eliminates the concatenation operator and optimizes the string. Example: Consider the below code: String str = "Geeks " +
2 min read
Easy Runtime Permissions in Android with Dexter
The Runtime Permission in Android which introduced in Marshmallow and due to these runtime permissions users can grant permission to the app in runtime, also while writing the code for runtime permissions. Sometimes handling the task of requesting permissions becomes so difficult and the developer has to write a huge amount of code. So we will see
7 min read
Differences between Dynamic Binding and Message Passing in Java
Dynamic Binding: In Dynamic binding compiler doesn’t decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method. Dynamic binding is also called Late binding. Message Passing: Message Passing in terms of computers is communication between processes. It is a for
3 min read
How to implement our own Dynamic Array class in Java?
Given task is to implement a class in Java which behaves just like the Dynamic array using ArrayList. ArrayList is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. ArrayList elements are placed in contiguous storage so that
4 min read
Mapping a Dynamic JSON Object Field in Jackson with Java
All REST API services are providing the resultant output either as XML or JSON pattern only as both are portable in nature and among that JSON is more popular. We can expect unknown properties in a JSON object. There are different ways available to map dynamic JSON objects into Java classes. They are obviously required in many scenarios. Let us cov
5 min read
Dynamic Class Data Sharing in Java with Example
In Java, a class is a template that defines the properties and behaviors of objects. Objects are instances of a class and can be created using the new keyword. A class typically consists of fields (also known as instance variables) and methods. Fields are variables that store data, and methods are blocks of code that perform a specific task. A clas
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg