Java Reference
In-Depth Information
In general, interfaces are preferred over abstract classes because an interface can define a
common supertype for unrelated classes. Interfaces are more flexible than classes. Consider
the Animal class. Suppose the howToEat method is defined in the Animal class, as follows:
interface preferred
abstract class Animal {
public abstract String howToEat();
Animal class
}
Two subclasses of Animal are defined as follows:
class Chicken extends Animal {
@Override
public String howToEat() {
return "Fry it" ;
Chicken class
}
}
class Duck extends Animal {
@Override
public String howToEat() {
return "Roast it" ;
Duck class
}
}
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