removed
0
Q:

what is polymorphism

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. Real life example of polymorphism: A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee.
7
 it is ability of a object to behave in multiple forms. 
 We use method overloading and overriding to achieve the polymorphism. 
 Occurs when a parent class reference is refer to a child class object. 
 If the super class is Abstract or Interface the class can only 
 be reference type. 
 For the abstract class object it must have to be extended regular class, 
 and for the interface it has to be implemented class.
• Overloading(static, compile time) mean same method name and 
different parameter, occur in same class. We can overload static, 
final and private methods. Return type can be different or same.
• Overriding(dynamic, runtime) means same method name and same parameter, 
occur in different class that has inheritance relationship(Is-A). 
We cannot override static, final and private methods. 
In method overriding return type must be same or coverient. 
static methods can not be override.
Ex: WebDriver(interface) driver = new ChromeDriver()(class);
=>we are initializing Chrome browser using Selenium WebDriver. 
It also means we are creating a reference variable (driver) of the interface 
(WebDriver) and creating an Object.
2
class Animal {
  public void animalSound() {
    System.out.println("The animal makes a sound");
  }
}

class Pig extends Animal {
  public void animalSound() {//override superclass method
    System.out.println("The pig says: wee wee");
  }
}

class Dog extends Animal {
  public void animalSound() {//override superclass method
    System.out.println("The dog says: bow wow");
  }
}

class Main {
  public static void main(String[] args) {
    //You can add all objects inherited from Animal to an Animal type list
    Animal[] animals = new Animal[3]; //Creating the Animal List
    animals[0] = new Animal(); //Add a new animal object to the list
    animals[1] = new Dog(); //Add a new dog object to the list
    animals[2] = new Pig(); //Add a pig object to the list
    for (Animal a: animals){
      a.animalSound(); //This statement prints the correct string no matter the class
    }
  }
}
2
The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form.
0

New to Communities?

Join the community