Polymorphism in Java 7
This tutorial describe concept of Polymorphism. It is one of OOPs concept.
Polymorphism :
As a name Polymorphism its concept is also same as many forms. It is very useful concept of OOPs and used in JAVA to customize developers code. You can implement this concept in Java by using method overloading and method overriding.
It is capability of an action or method to do different things based on the object that it is acting upon. You can say it is a feature that allows one interface to e used for a general class of actions.
Types of Polymorphism -
- Method Overloading
- Method Overriding
Example :
Here we are taking polymorphism example of method overloading, testValue() as method name is same but parameter declaration and return type is different. In first void testValue() we are simply printing some text. In next void testValue(int a) printing int value of a.In last int testValue(int a,int b) we are passing two arguments of int type and returning int type sum of both numbers. So you can see we used same function name but each time parameter declaration or return type is different. This is concept of method overloading.
class Overload { void testValue() { System.out.println("It is just a test"); } void testValue(int a) { System.out.println("It is int value : " + a); } int testValue(int a, int b) { return a + b; } } public class MethodOverloading { public static void main(String[] args) { Overload overload = new Overload(); overload.testValue(); overload.testValue(20); System.out .println("Sum of two numbers : " + overload.testValue(30, 40)); } }
Output :
It is just a test It is int value : 20 Sum of two numbers : 70