You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/* In this example Pet variable behaves polymorphic because it can be either Cat or Dog. The method makeSound() overridden in sub class Dog and Cat. */
importjava.util.ArrayList;
importjava.util.List;
abstractclassPet{
publicabstractvoidmakeSound();
}
classCatextendsPet{
@Override
publicvoidmakeSound() {
System.out.println("Cat makes Meow sound");
}
}
classDogextendsPet{
@Override
publicvoidmakeSound() {
System.out.println("Dog makes Woof sound");
}
}
publicclassMethodOverrideDemo1{
publicstaticvoidmain(Stringargs[]) {
//Now Pet will show How Method Overriding works in Java
List<Pet> pets = newArrayList<Pet>();
pets.add(newCat());
pets.add(newDog());
//pet variable which is type of Pet behave different based