OOPS concepts in Java
Java tutorials for beginners
Java basics concepts
Java Objects and Classes
What is Inheritance in Java?
What is Abstraction in Java?
What is Interface in Java?
What is Abstract Class in Java?
What is Polymorphism in Java?
What is Encapsulation in Java?
Java programming example
How Java Program Work?
Hello World in Java
Java basics for beginners
Polymorphism:
Polymorphism is the ability to many
forms of an object. The most common use of Polymorphism is parent class
reference is used to a child class object.
There are two types of Polymorphism in java
1. Compile time Polymorphism (method overloading).
2. Runtime Polymorphism (method overriding).
1. Compile time
Polymorphism (method overloading).
Overloading is
compile time polymorphism where more than one methods share the same name with
different parameters or signature.
Example:
class TestOverloading
{
public void
display(char c)
{
System.out.println(c);
}
public void
display(char c, int num)
{
System.out.println(c
+ " "+num);
}
}
class TestMainClass
{
public static
void main(String args[])
{
TestOverloading
obj = new TestOverloading ();
obj. display('a');
obj. display('a',10);
}
}
2.
Runtime
Polymorphism (method overriding).
Overriding is run
time polymorphism having same method with same
parameters or signature, but associated in a class & its
subclass.
Example:
class Eat{
//Overridden method
public void eat()
{
System.out.println("Eating");
}
}
class Rice extends Eat {
//Overriding method
public void eat(){
System.out.println("He is eating rice");
}
public static void main( String args[]) {
Rice obj = new Rice ();
//This will call the child class version of eat()
obj.eat();
}
}
1. Compile time Polymorphism (method overloading).
Overloading is compile time polymorphism where more than one methods share the same name with different parameters or signature.
Example:
class TestOverloading
{
public void
display(char c)
{
System.out.println(c);
}
public void
display(char c, int num)
{
System.out.println(c
+ " "+num);
}
}
class TestMainClass
{
public static
void main(String args[])
{
TestOverloading
obj = new TestOverloading ();
obj. display('a');
obj. display('a',10);
}
}2. Runtime Polymorphism (method overriding).
Overriding is run time polymorphism having same method with same parameters or signature, but associated in a class & its subclass.
Example:
class Eat{
//Overridden method
public void eat()
{
System.out.println("Eating");
}
}
class Rice extends Eat {
//Overriding method
public void eat(){
System.out.println("He is eating rice");
}
public static void main( String args[]) {
Rice obj = new Rice ();
//This will call the child class version of eat()
obj.eat();
}
}