Object Oriented Programming - JAVA - Polymorphism

 

Object Oriented Programming - JAVA 👽

Polymorphism is the ability of any data to hold more than one form. Plural means many, and morph means the same word as categories. Polymorphism is an important concept in object-oriented programming languages.
Before when we learn polymorphism, we have to know about override and casting. If you have no idea about those things then you can use below links.


After overriding a method in a superclass in a subclass, the process of upcasting and calling the subclass method through the superclass reference is called Polymorphism.

class A {
  void print (){
    sout ("A");
  }
}
class B extends A{ 
  void print (){
    sout ("B");
  }
}
class Test {
  public static void main(String args[]){
    B b = new B();
    b.print();        //Output : B
    A a = new A();
    a.print();        //Output : A
    A a1 = new B();   //Upcasting
    a1.print();       //Output : B
  }
}

The code is run line by line. Therefore, when input is given, all the lines from the beginning will be run regardless of the input. By, polymorphism, you can bypass it and run the relevant object.
Let's see an example.

class Products {
  void store (){}
}
class Lux extends Products {
  Lux(String a){
     a = "Lux";
  }
  void store(){
    //store code
  }
}
class Sunsilk extends Products {
  Sunsilk(String a){
     a = "Sunsilk";
  }
  void store(){
    //store code
  }
}
class Glow&Lovely extends Products {
  Glow&Lovely(String a){
     a = "Glow&Lovely";
  }
  void store(){
    //store code
  }
}
class Test {
  public static void main(String args[]){
    Product l = new Lux(" ");
    Product s = new Sunsilk(" ");
    Product g = new Glow&Lovely(" ");
  }
}

When there are several selections, a superclass must inherit and override all the necessary classes, so a meaningless method is created inside the superclass. At the end we can call the subclasses when the creation of upcasting objects. Then we can call the particular object for the particular input.

Let's meet in the next blog to discuss about Abstraction / Abstract classes.

https://miyurangika1223.blogspot.com/2024/03/object-oriented-programming-java_18.html


Comments

Popular posts from this blog

Sorting Algorithms - JAVA👽

Object Oriented Programming - JAVA- class boundary, variable types, modifiers, java main method

Object Oriented Programming - JAVA- Method Overriding