Oop 2
Oop 2
Types of Polymorphism
In Java polymorphism is mainly divided into two types,
1. Compile-time Polymorphism
2. Runtime Polymorphism
Compile-time polymorphism
It is also known as static polymorphism.
This type of polymorphism is achieved by function overloading.
Runtime polymorphism
It is also known as Dynamic Method Dispatch.
It is a process in which a function call to the overridden method is resolved at Runtime.
This type of polymorphism is achieved by Method Overriding.
Method overriding, on the other hand, occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to be overridden.
Method Overloading
In Java it is possible to define two or more methods within the same class that share the same name,
as long as their parameter declarations are different.
When this is the case, the methods are said to be overloaded, and the process is referred to as
method overloading.
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading.
Method overloading is one of the ways that Java supports polymorphism.
As we can see, method( ) is overloaded three times.
integer parameters.
Example,
class OverloadDemo {
void method() // Overload method with no arguments
{
System.out.println("No parameters");
}
void method(int a) // Overload method for one integer parameter.
{
System.out.println("a: " + a);
}
void method(int a, int b) // Overload method for two integer parameters.
{
System.out.println("a and b: " + a + " " + b);
}
double method(double a) // overload method for a double parameter
{
System.out.println("double a: " + a);
return a*a;
}
}
class OverloadExample
{
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.method(); // call all versions of method()
ob.method(10);
ob.method(10, 20);
result = ob.method(123.25);
System.out.println("Result of ob.method(123.25): " + result);
}
}
class Adder{
static int add(int a,int b)
{
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as a method
in its superclass, then the method in the subclass is said to override the method in the superclass.
class Shape
{
void draw()
{
System.out.println("Inside the method of Parent class ");
System.out.println("Drawing Shapes");
}
}
//Derived class
class Circle extends Shape
{
//Overriding method of base class with different implementation
@Override
void draw()
{
System.out.println("Inside the overridden method of the child class ");
System.out.println("Drawing Circle");
}
}
//Driver class
public class MethodOverridingDemo
{
public static void main(String args[])
{
//creating object of Base class Shape - If a Parent type reference refers
// to a Parent object, then Parent's draw() method is called
Shape obj = new Shape();
Output:
Inside the method of Parent class
Drawing Shapes
Inside the overridden method of the child class
Drawing Circle
1. All concepts