Polymorphic parameters Flashcards
Define polymorphic parameters with an example !
A polymorphic parameter is a parameter type that can be an interface or a super class that allows it to accept multiple types during method invocation
Give an example of a method that takes a super class as a parameter and then call it with a plethora of subclass variable subtypes !
public class Reptile {
public String getName() {
return “Reptile”;
}
}
public class Alligator extends Reptile {
public String getName() {
return “Alligator”;
}
}
public class Crocodile extends Reptile {
public String getName() {
return “Crocodile”;
}
}
public class ZooWorker {
public static void feed(Reptile reptile) {
System.out.println(“Feeding reptile “+reptile.getName());}
public static void main(String[] args) {
feed(new Alligator());
feed(new Crocodile());
feed(new Reptile());
}
}
Give an example of a good coding practice when you use the interface variable type over the class type for great reusability !
It is generally considered a good practice in Java to use reference variables of interface types or super classes when instantiating classes, especially when you want to emphasize flexibility and adhere to good design principles