How to achieve Dynamic or Static polymorphism in Java? Polymorphism refers to the ability of an object to behave differently to the same message. Polymorphism is of two types. static or dynamic. In dynamic polymorphism the response to message is decided on run-time while in static polymorphism it is decided on compile-time. The assignment of data types in dynamic polymorphism is known as late or dynamic binding. In dynamic binding method call occur based on the object (instance) type at Run time. Eg: method overriding If the assignment of data types is in compile time it is known as early or static binding. In static binding method call occur based on the reference type at compile time. Eg: method overloading Method Overloading - This means creating a new method with the same name and different signature. It uses early binding. Method Overriding - This is the process of giving a new definition for an existing method in its child class. All object created at run time on the heap therefore actual binding is done at the runtime only. Method overloading would be an example of static polymorphism, whereas overriding would be an example of dynamic polymorphism. And Method overloading would be achieved as follows: Code: /*Method Overloading*/
void Method1(){}
} void main()
/*Method overriding*/ class Method1{
class Method2{
void main()
--- Method overloading and overriding both can be done in Static and dynamic polymorphism. It all depends on when the right method selection is being done. i.e., it depends on the type of method we use for overloading and overriding. Method overloading and overriding using Instance methods come under runtime/dynamic polymorphism Method overloading and overriding using static/private/final methods come under compile time/static polymorphism Please remember overriding is not possible using private and final methods. Please find the example below proving that method overriding is an example of Dynamic polymorphism. //verify overriding using Instance methods
class Sample
void display()
System.out.println("\nSample class display() method"); } }
class Demo extends Sample
void display1()
System.out.println("\nDemo classs display() method"); } }
class Poly2
public static void main(String args[])
Demo d = new Demo(); d.display(); } }
/* In the above program sample class display method will
be called.
It means, if a method is called using subclass object,
JVM searches for the method in both subclass and super class.
Thus overriding is also done dynamically. Hence, Method Overriding is not only Static polymorphism but also a form of dynamic polymorphism. So it all depends on the type of method used for overloading as explained in the begining.
Do you have a Java Problem?
Java Books
Return to : Java Programming Hints and Tips All the site contents are Copyright © www.erpgreat.com
and the content authors. All rights reserved.
|