Java Reference
In-Depth Information
classes. Consider the Animal class. Suppose the howToEat method is defined in the
Animal class, as follows:
abstract class Animal {
Animal class
public abstract String howToEat()
;
}
Two subclasses of Animal are defined as follows:
class Chicken extends Animal {
@Override
Chicken class
public
String howToEat()
{
return "Fry it" ;
}
}
class Duck extends Animal {
@Override
Duck class
public String howToEat()
{
return "Roast it" ;
}
}
Given this inheritance hierarchy, polymorphism enables you to hold a reference to a Chicken
object or a Duck object in a variable of type Animal , as in the following code:
public static void main(String[] args) {
Animal animal = new Chicken();
eat(animal);
animal = new Duck();
eat(animal);
}
public static void eat(Animal animal) {
animal.howToEat();
}
The JVM dynamically decides which howToEat method to invoke based on the actual object
that invokes the method.
You can define a subclass of Animal . However, there is a restriction: The subclass must be
for another animal (e.g., Turkey ).
Interfaces don't have this restriction. Interfaces give you more flexibility than classes,
because you don't have to make everything fit into one type of class. You may define the
howToEat() method in an interface and let it serve as a common supertype for other classes.
For example,
public static void main(String[] args) {
Edible stuff = new Chicken();
eat(stuff);
stuff = new Duck();
eat(stuff);
stuff = new Broccoli();
eat(stuff);
}
Search WWH ::




Custom Search