19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

classes. Consider the Animal class. Suppose the howToEat method is defined in the<br />

Animal class, as follows:<br />

15.8 Interfaces vs. Abstract Classes 583<br />

abstract class Animal {<br />

public abstract String howToEat() ;<br />

}<br />

Animal class<br />

Two subclasses of Animal are defined as follows:<br />

class Chicken extends Animal {<br />

@Override<br />

public String howToEat() {<br />

return "Fry it";<br />

}<br />

}<br />

class Duck extends Animal {<br />

@Override<br />

public String howToEat() {<br />

return "Roast it";<br />

}<br />

}<br />

Chicken class<br />

Duck class<br />

Given this inheritance hierarchy, polymorphism enables you <strong>to</strong> hold a reference <strong>to</strong> a Chicken<br />

object or a Duck object in a variable of type Animal, as in the following code:<br />

public static void main(String[] args) {<br />

Animal animal = new Chicken();<br />

eat(animal);<br />

}<br />

animal = new Duck();<br />

eat(animal);<br />

public static void eat(Animal animal) {<br />

animal.howToEat();<br />

}<br />

The JVM dynamically decides which howToEat method <strong>to</strong> invoke based on the actual object<br />

that invokes the method.<br />

You can define a subclass of Animal. However, there is a restriction: The subclass must be<br />

for another animal (e.g., Turkey).<br />

Interfaces don’t have this restriction. Interfaces give you more flexibility than classes,<br />

because you don’t have <strong>to</strong> make everything fit in<strong>to</strong> one type of class. You may define the<br />

howToEat() method in an interface and let it serve as a <strong>com</strong>mon supertype for other classes.<br />

For example,<br />

public static void main(String[] args) {<br />

Edible stuff = new Chicken();<br />

eat(stuff);<br />

stuff = new Duck();<br />

eat(stuff);<br />

}<br />

stuff = new Broccoli();<br />

eat(stuff);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!