can anybody brief it
what is difference between static and dynamic polymorphism?
Collapse
X
-
Tags: None
-
Static polymorphism involves early binding or compile time binding whereas dynamic polymorphism uses
late binding or run time binding. The term static polymorphism is associated with overloaded methods
because it gives the impression that a single named method will accept a number of different argument types. The System.out.prin tln() method is an example that may take String or Object references, boolean and
other primitive types as an argument. In fact, each overloaded method is separate and the compiler can see the difference between them. In this case, the argument types are fixed at compile time and are considered static. This has nothing to do with the Java keyword
static. Dynamic polymorphism is where a class overrides a superclass method or implements an interface. For example, any class may override the Object.toString () method and provide its own implementation, and this
is known at compile time. However, for a simple Java program that initiates a series of objects and calls their toString() method, the compiler does not consider the object references differently. Any differences in the objects' toString() implementations are only seen
at runtime, so they are considered dynamic. -
Some may also argue that the dynamic polymorphism is faster than the static. But that has little or no bearing in the wider aspect of the application.Comment
-
Wouldn't static polymorphism be faster than dynamic polymorphism? Since as you say static polymorphism is resolved at compile time where dynamic polymorphism is resolved at run time through a look up with the VTable then static polymorphism is going to be faster.Comment
-
It's not a question of speed. If the object is created at run time, then the type can't be determined at compile time.
There is no way to know the type of the object ptr points at when you compile.Code:Base* ptr = new Derived
The "static" polymorphism in C++ is function overloading. The example above is the dynamic polymorphism. It is the dynamic version that uses the vtbl.Comment
-
Comment