Ankur Nirmalkar
Ankur Nirmalkar

Reputation: 143

Whats the real time example of dynamic polymorphism in java

What is the real time example of dynamic polymorphism in java?

I have been asked so many places this question in interview but dint got real answer. Code:

class A {
    public void m1() {}
}

class B extends A {
    public void m1() {}
}

class manage {
    A a1 = new A();
    B b1 = new B();
    A a2 = new B();

    //when i will call A's m1 it will call m1 of A
    a1.m1();

    //when i will call B's m1 it will call  m1 of B
    b1.m1();

    //when i will call B's m1
    a2.m1();

}

in the above code by looking , i can say its whose object will be called then why its run time polymorphism

Anyone can please help the real time correct example of runtime/dynamic polymorphism ??

Upvotes: 2

Views: 751

Answers (3)

user10239771
user10239771

Reputation:

As the name suggests, it happens in realtime aka runtime.

Upvotes: 0

nguyentt
nguyentt

Reputation: 669

"Dynamic polymorphism is the polymorphism existed at run-time".

That mean Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at run-time.

In your example, the compiler don't know the behavior of a2.m1(). However, at the runtime, the JVM will invoke the code which was defined in the class B.

class A {
    public void m1(){
        System.out.println("Inside A's m1 method");
    }
}

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

class C extends A {
     public 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();
        a.m1(); // calling m1 of A

        a = new B();
        a.m1(); // calling m1 of B

        a = new C();
        a.m1(); // calling m1 of C

    }
}

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

Upvotes: 1

GhostCat
GhostCat

Reputation: 140417

Lets change your code example just a little bit. Instead of having a test class that defines the objects to test, we only offer a method taking some arguments:

public void testCalls(A a1, A b1, A b2) {
  a1.m1();
...

Now, can you still say what will happen? "Hmm, that will depend on what gets passed to the method call?!"

In your example, you know what is going to happen because you can easily deduct the true nature of all objects. But what if you don't have that information? When you are only providing an interface, and the incoming objects aren't showing up in your source code?!

Thus: what matters is the true type of an object at runtime. Of course, when you construct a simple example, you always know that true type. But the things that matter in the real world are simply not that simple.

Upvotes: 4

Related Questions