Learn Java lessons onlIne Java is a high-level programming language developed by Sun Microsystems but later was taken over by Oracle. This tutorial gives a basic understanding on Polymorphism. What is Polymorphism? The ability of an object to take many forms is Polymorphism. The most common use of polymorphism in OOP occurs when a parent class reference is used to mention to a child class object. Any Java object that can pass more than one IS-A test is considered to be polymorphic.
Key points: This
feature allows one interface to be used for many class of actions. An operation may show different behavior in different instances. Types of data used in the operation decide the behavior Polymorphism is extensively used in executing inheritance. Two types of polymorphism available in JAVA are: 1) Method Overloading 2) Method Overriding
1)Method
Overloading:
With
different argument list or parameters,in Java it is possible to define two or more methods of same name in a class. This concept is called Method Overloading. An overloaded method can throw different expectations. And it can have different access modifiers.
Rules
for Method Overloading Change method signature. Return type method is never part of method signature, so only changing the return type of method does not amount to method
Example: class {
Overload
void demo (int a) { System.out.println ("a: " + a); } void demo (int a, int b) { System.out.println ("a and b: " + a + "," + b); } double demo(double a) { System.out.println("double a: " + a); return a*a; }
Here
the method demo() is encumbered 3 times: first having 1 int parameter, second one has 2 int parameters and third one is having double arg. The methods are implored with the same type and number of variable used. Output: a: 10 a and b: 10,20 double a: 5.5 O/P : 30.25
2)
Method Overriding
In
method overriding, child class overrides the parent class method without even touching the source code of the base class. Child class has the same method as of base class.
Rules
for Method Overriding: Only inherited methods can be overridden object type determines which overridden method will be used at execution. Overriding method can have different result type Abstract methods must be overridden What can't be overridden are constructors and
class {
Vehicle
public void move () { System.out.println ("Vehicles are used for moving from one place to another "); } } class Car extends Vehicle { public void move () { super. move (); // invokes the super class method System.out.println ("Car is a good medium of transport "); }