JAVA OOPs Concepts

Polymorphism:- Polymorphism allows one interface to be used for set of actions i.e one name may refer to different functionality
Polymorphism allows a object to accept different requests of a client
Types of Polymorphism
1. compile-time polymorphism
2. runtime polymorphism

In compile-time polymorphism, method to be invoked is determined at the compile-time. Compile time polymorphism is supported through the method overloading.

Method overloading means having multiple method with the same name but with different signature(number, type, and order of parameters).

EXAMPLE OF COMPILE-TIME POLYMORPHISM:-

class A
{
public void fun1(int x) {
system.out.println("int");
}
public void fun1(int x, int y)
{
system.out.println("int and int");
}
}

public class B
{
public static void main(String[] arg)
{
A obj = new A();
obj.fun1(2);
obj.fun1(2,3);
}
}

In runtime polymorphism, the method to be invoked is determined at runtime. The example of runtime polymorphism is method overriding.

Method Overriding means a subclass contains a method with the same name and signature as in the super class then it is called as method overriding.

EXAMPLE OF RUNTIME POLYMORPHISM:-

class A
{
public fun1(int x)
{
System.out.println("int in A");
}
public void fun1(int x, int y)
{
System.out.println("int and int in B")
}
}

class C extends A
{
public void fun1(int x)
{
System.out.println("int in C");
}
}

public class D
{
public static void main(String[] arg)
{
A obj;
obj = new A();
obj.fun1(2);            \\ prints "int in A"
obj = new C();
obj.fun1(2);            \\ prints "int in C"
}
}

Comments

Popular posts from this blog

NICOSIA