Poly means many. Polymorphism in java defines a single super class and that can be used for any sub classes. Even the class definition can be overridden and the methods can be overloaded with another definition.
The method
overriding and method overloading java implementations are given below….
Java
Program to implement Method overriding:
Overriding is the process of redefining a
function. This program overrides a function definition.
Steps:
- · Create a super class “Fruit” with a
member function “color()” with a output statement.
- · Next, create a sub class “Apple”
extends from super class “Fruit” with the function “color()”. Override the function
with another definition.
- · Write a class “samplePoly” with main
function.
- · Fruit myFruit = new Apple(); Using the base class, declare an object for
sub class.
- · Call the sub class’s overridden function
using the object.
class Fruit
{
void color() {
System.out.println("Each Fruit has
a color");
}
}
class Apple
extends Fruit {
@Override
void color() {
System.out.println("Color of Apple
is Red");
}
}
public
class samplePoly {
public static void main(String[] args) {
Fruit myFruit = new Apple(); // Creating an object for Apple - Overriden
myFruit.color(); // Calling the overridden function
}
}
Here is the
output.
C:\raji\blog>javac samplePoly.java
C:\raji\blog>java samplePoly
Color of
Apple is Red
Method
overloading is given below.
Java
Program to implement Method overloading:
“Same function name with different arguments” – A class can have many
functions with same name with different arguments.
- Class “MathExpression”.
- mul() is a function which is having two different arguments.
- First mul() function gets two arguments,multiply it and return the output.
- Second mul() function gets three arguments, multiply it and return the result.
“sampleOverload.java”
class
MathExpression {
int mul(int x, int y) {
return x * y;
}
int mul(int x, int y, int z) {
return x * y * z;
}
}
public
class sampleOverload {
public static void main(String[] args) {
MathExpression oper = new
MathExpression();
System.out.println("The
multiplication of two numbers are : "+oper.mul(5, 7));
System.out.println("The Overloaded
multiplication of three numbers are : "+oper.mul(4, 6, 8));
}
}
Output:
C:\raji\blog>javac
sampleOverload.java
C:\raji\blog>java
sampleOverload
The
multiplication of two numbers are : 35
The Overloaded
multiplication of three numbers are : 192
This is the
implementation of Polymorphism in java. This fundamental concept is useful for
its flexibility and reusability.
No comments:
Post a Comment