POLYMORPHISM

What is Polymorphism?

Polymorphism means many forms. When one thing take many form then it is Polymorphism.

For Example: Addition of two things: When we add two number then it is addition but when we add two words it is concatenation. Here, addition take two forms for adding two things depending on condition.

There are two types of Polymorphism:

  • Overriding
  • Overloading

Overriding: Overriding is when there is same signature but different class. Suppose we have created method named as test() then we will use same method in two classes with the help of inheritance. We will use same method in both class but block of code in both class will be different. Overriding can only take place when inheritance happens. Overriding is run time polymorphism.

For example:

class A { // parent class

public void test(){ // method

System.out.println(“from A”); } }

class B extends A { // child class as inheritance take place

public void test() { // used same method of class A

System.out.println(“from B”);} // modified statement

public static void main() {

B b1 = new B();

b1.test(); }}

Output: from B // as we call method of class B

Overloading: Overloading is happen when there is same class but different signature. There is no need of inheritance here. We we create class and method, we will same one method in same class only by differing the arguments in method. Overloading is compile time polymorphism.

For example:

class A {

public void test() {

System.out.println(” From no argument”); }

public void test(int a, int b) { // same method is used in same class by putting arguments

System.out.println(a);

System.out.println(b);

}

Public static void main() {

A a = new a();

a.test();

a.test(10,20);

}}

Output:

From no argument

10 20

We will be happy to hear your thoughts

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!๐Ÿ‘‹
Can we help you?