13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

86Chapter 3An Experienced Programmer’s Introducti<strong>on</strong> to Java3.4.2 InheritanceInheritance is how a class places itself in a hierarchy of existing classes. In Java,each class inherits from exactly <strong>on</strong>e existing class. A class names the class fromwhich it inherits with the extends keyword. We said a Java class inherits fromexactly <strong>on</strong>e class, and yet our Example 3.24 doesn’t c<strong>on</strong>tain the extendskeyword. What gives?If a class doesn’t explicitly extend an existing class, it implicitly extendsthe “root” Java class, Object. The Object class has some interesting features,and the fact that all Java classes directly or indirectly extend Object hasinteresting c<strong>on</strong>sequences that we will explore later.Pers<strong>on</strong>s coming to Java from another object-oriented language whosename shall remain C++ might w<strong>on</strong>der about multiple inheritance. Java has thec<strong>on</strong>cept of interfaces. An interface is like a class, except that it may not c<strong>on</strong>taindata 10 and may c<strong>on</strong>tain <strong>on</strong>ly method definiti<strong>on</strong>s, without any implementati<strong>on</strong>(Example 3.25). An interface may not be instantiated (created with the newoperator), 11 so how do you make use of interfaces? Well, a class extends exactly<strong>on</strong>e existing base class, but it may implement any number of interfaces by usingthe implements keyword (Example 3.26).Example 3.25 An interfacepublic interfaceIdentifiable{public int getID();}As you can see, a class that implements an interface must provide an implementati<strong>on</strong>of all the methods defined in the interface. We said that an interfacecannot be instantiated, but you can declare a variable of type Identifiable10. Actually, an interface may c<strong>on</strong>tain final static data, but since we haven’t introducedthese c<strong>on</strong>cepts yet, just pretend interfaces cannot c<strong>on</strong>tain data for now and we’ll put the lie toit later.11. Although you can do something that looks suspiciously like it with an<strong>on</strong>ymous innerclasses—but since we haven’t introduced these c<strong>on</strong>cepts yet, just pretend that you cannot instantiatean interface; you will see such use later.

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

Saved successfully!

Ooh no, something went wrong!