| written 9.1 years ago by | • modified 9.1 years ago |
Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology
Marks: 5M
Year: Dec 2014
| written 9.1 years ago by | • modified 9.1 years ago |
Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology
Marks: 5M
Year: Dec 2014
| written 9.1 years ago by |
Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations.
Following concepts demonstrate different types of polymorphism in java.
Method Overloading
In Java, it is possible to define two or more methods of same name in a class, provided that there argument list or parameters are different. This concept is known as Method Overloading.
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;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Here the method demo() is overloaded 3 times: first having 1 int parameter, second one has 2 int parameters and third one is having double arg. The methods are invoked or called with the same type and number of parameters used.
Method Overriding
Child class has the same method as of base class. In such cases child class overrides the parent class method without even touching the source code of the base class. This feature is known as method overriding.
Example:
public class BaseClass
{
public void methodToOverride() //Base class method
{
System.out.println ("I'm the method of BaseClass");
}
}
public class DerivedClass extends BaseClass
{
public void methodToOverride() //Derived Class method
{
System.out.println ("I'm the method of DerivedClass");
}
}
public class TestMethod
{
public static void main (String args []) {
// BaseClass reference and object
BaseClass obj1 = new BaseClass();
// BaseClass reference but DerivedClass object
BaseClass obj2 = new DerivedClass();
// Calls the method from BaseClass class
obj1.methodToOverride();
//Calls the method from DerivedClass class
obj2.methodToOverride();
}
}