This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Guys, I read some messages in the forum which use Dynamic Polymorphism and Method Overriding synonymously. It is WRONG!! Dynamic Polymorphism occurs when subclass methods are called using base class reference. When you are not using base class reference to access overriden methods, it is Compile Time Polymorphism. //Dynamic Polymorphism Base b = new Derived(); b.OverridenMethod(); //Compile Time Polymorphism Derived d = new Derived(); d.OverridenMethod(); In both the above cases, same method is called.
SCJP 1.4<p>Wingardium Leviosa!!
Joined: Oct 31, 2002
FYI, Method Overloading is always Compile Time polymorphism.
FYI, Method Overloading is always Compile Time polymorphism. Wohwohwoh not that fast, that's not quite correct! What about the following code:
The created object is of type Test but referenced using the base class reference. method1() is overloaded in SuperTest and in Test... method1 cannot be resolved at compile-time and if you try to decompile (using javap) you get the following bytecode:
On line 11, you can see that method1 is invoked using invokevirtual which means that method1 is looked up dynamically based on the runtime type of the object.
You get the exact same bytecodes for main() if you remove the method "public void method1(Object o)" entirely. Overloading is a non-issue here. The invokevirtual occurs because, as far as the compiler is concerned, "t" could be some other subclass of SuperTest that has overridden "public void method1 (String s)".
Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Joined: Aug 26, 2001
I agree that method1 in class Test is not useful for the problem at hand since both method1 declared in SuperTest are inherited. This was just to demonstrate that overloaded methods may not be resolved at compile time as Don claimed.
Joined: Jun 06, 2002
But, given that the bytecode is identical whether or not there is overloading, I'm not convinced by this example. Even if you take out "public void method1(int i)", thus removing all overloading, the compiler generates the same bytecode for main(). [ November 01, 2002: Message edited by: Ron Newman ]