While the basic principle of polymorphism unleashes “which of whom” in terms of types , but what confuses me is how it clarifies the method invocation method and invokes the correct method body in polymorphism.
Since in java the whole binding of the late-binding method is if the method is not static , final or private , and the late binding is done by the JVM, which pre-computes the method table for each class and then makes a table at runtime during a normal call to the call.
But the same thing happens with polymorphism. for instance
Suppose I have a common Cycle class with the ride() method
class Cycle { public void ride(){ System.out.println("I'm Riding generic Cycle()"); } }
And I have three specialized classes, Bicycle Tricycle and Unicycle , which extend the general Cycle class and override its ride() method.
class Bicycle extends Cycle { public void ride() { System.out.println("I'm riding Bicycle"); } } class Tricycle extends Cycle{ public void ride() { System.out.println("I'm riding Tricycle "); } } class Unicycle extends Cycle { public void ride() { System.out.println("I'm Riding Unicycle "); } }
This is the TestRide class to test the above polymorphism.
public class TestRide { public static void ride(Cycle c){ c.ride(); } public static void main(String[] args){ Cycle Cycling = new Cycle(); ride(Cycling); Bicycle bi = new Bicycle(); ride(bi); Tricycle tri = new Tricycle(); ride(tri); Unicycle uni = new Unicycle(); ride(uni); } }
Output
I'm Riding generic Cycle() I'm riding Bicycle I'm riding Tricycle I'm Riding Unicycle
Bytecode:
public static void main(java.lang.String[]); flags: ACC_PUBLIC, ACC_STATIC Code: stack=2, locals=5, args_size=1 0: new #17
Even in the byte encoder, as usual, a call is invoked with invokestatic and invokespecial , while I thought that it would use invokedynamic to determine the version of the method suitable for the actual type of the object. But that was not so.
So, how does Java compute the actual method call during polymorphism, while we just pass the object up in the ride() method, like ride(bi) in the TestRide class?
EDIT: RIDE ByteCode Method
public static void ride(com.polymorphism.Cycle); flags: ACC_PUBLIC, ACC_STATIC Code: stack=1, locals=1, args_size=1 0: aload_0 1: invokevirtual #16