Read an Excerpt
Chapter 5: How to work with inheritance and interfacesNow that you've learned how to code classes that define objects, you're ready to learn how to work with inheritance, interfaces, and other object-oriented features of Java. Although these features are difficult conceptually, they are critical to the effective use of Java. That's why they can't be put off until later in this book.
You don't, however, have to master everything that's presented in this difficult chapter in one reading. Instead, you can focus on the concepts and terms the first time through it. Then, you can refer back to this chapter whenever you need to refresh your memory about concepts, terms, or coding details.
How to work with inheritance ..... 150
An introduction to inheritance ..... 150
How to code a class that inherits the BookOrder class ..... 152
How to code a class that inherits the JFrame class ..... 154
What you should know about polymorphism ..... 154
How to work with the Object class ..... 156
The methods of the Object class ..... 156
How to cast objects ..... 158
How to override the to String method ..... 160
How to override the equals method ..... 162
How to use the Class class to get information about an Object object ..... 164
More skills for coding classes and methods ..... 166
How to code a method that throws an exception ..... 166
How to work with abstract classes and methods ..... 168
How to work with final classes and methods ..... 170
How to work with access modifiers ..... 172
How to use the this keyword ..... 174
How primitive types and objects are passed to a method ..... 176
How to work with interfaces ..... 180
An introduction to interfaces ..... 180
How to code an interface ..... 182
How to implement an interface ..... 184
How to use an interface as an argument ..... 186
How to implement the Cloneable interface ..... 188
How to code classes that are closely related ..... 190
How to code more than one class per file ..... 190
An introduction to nested classes ..... 192
Perspective ..... 194
How to work with inheritanceInheritance is one of the critical concepts of object-oriented programming and Java programming. It lets you create a class that inherits fields and methods from another class. These fields and methods can be referred to as members.
An introduction to inheritance
Figure 5-1 introduces you to inheritance. To use it, you create a subclass that inherits the public and protected fields and methods from a superclass. In addition, it inherits all superclass members that have no access modifier as long as the superclass and subclass are in the same package. Then, the objects that are created from the subclass can use these members of the superclass. In addition, though, the subclass can define its own methods. It can also define methods with the same names and signatures of methods in the superclass. In that case, the methods of the subclass override the methods in the superclass.
This is illustrated by the first diagram in this figure, which shows a subclass named DiscountBookOrder that inherits the BookOrder class that you were introduced to in the last chapter. Since the DiscountBookOrder class inherits all of the public methods from the BookOrder class, you can call any of those methods from an object created from the DiscountBookOrder class. In addition, though, the DiscountBookOrder class provides three new methods (setPercentOff, getSubtotal, and getPercentOff). It also provides two methods that will override the ones with the same signatures in the BookOrder class (setTotal and getTotal).
The second diagram shows part of an inheritance hierarchy that's taken from the Java API. Although this diagram only shows three levels of inheritance, Java provides for an unlimited number. In addition, this diagram shows that a superclass can have more than one subclass. In this case, the Window superclass has two subclasses, but here again Java provides for an unlimited number. In the Java API, for example, some classes have dozens of subclasses.
As you become more familiar with the classes of the Java API, you'll find that they make widespread use of inheritance. You'll also discover that you have to use inheritance when you create a graphical user interface for an application. In this case, a class that you create inherits the fields and methods from the Java Frame class. You'll see this illustrated in figure 5-3.
If you think you need to use inheritance as you plan the classes for an application, you should make sure that the subclass has an is-a relationship with its superclass. This means that the subclass is a type of the superclass. For instance, a discount book order is a type of book order, and a frame is a type of window.
Incidentally, in this book, we'll primarily use the terms superclass and subclass to refer to the classes in an inheritance hierarchy. However, a superclass can also be called a base or parent class, and a subclass can also be called a derived or child class.
- Inheritance lets you define a class that inherits all of the public and protected fields and methods of an existing class. Then, the class that inherits the fields and methods is called a subclass, derived class, or child class, while the class that is being inherited is called a superclass, base class, or parent class.
- In a subclass, you can define fields and methods that aren't in the superclass. You can also define methods that have the same names and signatures as those in the superclass. In that case, the method in the subclass overrides the method in the superclass.
- Inheritance is used to model an is-a relationship. In other words, inheritance is used when a subclass is a type of the superclass.
- Inheritance is commonly used in the classes that are in the Java API, so you often need to know what the inheritance hierarchy is as you use Java classes.
How to code a class that inherits the BookOrder classFigure 5-2 shows how to code the DiscountBookOrder subclass that inherits the BookOrder class as shown in the previous figure. Whenever you create a subclass, you use the extends keyword to indicate that the subclass extends the superclass. Then, you code the instance variables, constructors, and methods for the subclass. As you do that, you can use the super keyword to call the constructors and methods in the superclass.
If you study the code for the DiscountBookOrder class in this figure, you can see that its declaration extends the BookOrder class. Then, it provides four new instance variables, a constructor, three new methods, and two methods that will override methods in the superclass (setTotal and getTotal).
Since a subclass can't inherit constructors, the DiscountBookOrder class must define its own constructor. The constructor for this subclass has three parameters: the book code that indicates the book that's ordered; the quantity of books ordered; and a key code that indicates what (if any) discount should be taken. After the parameter list, the constructor initializes all of the variables in the superclass and the subclass. First, it uses the super keyword to call the constructor for the superclass. This initializes the three instance variables of the superclass. Then, it initializes the three new instance variables by assigning the third parameter to the discountCode variable and by calling the setPercentOff and setTotal methods.
The first two methods in the DiscountBookOrder class set the instance variables of the class. The setPercentOff method sets the percentOff instance variable based on the value of the discountCode instance variable. Then, the setTotal method sets the subtotal and total instance variables. To do that, it uses the super keyword to call the getQuantity and getBook methods of the BookOrder class, and it uses the getPrice method of the Book class to return the price.
The last three methods in the subclass are get methods that return the subtotal, percentOff, and total variables. Because they're so simple, these methods are coded in single lines instead of the expanded format that you're used to seeing.
After the code for this subclass, you can see the code for a driver class named OverrideTest that tests the DiscountBookOrder class. To do that, the driver creates a DiscountBookOrder object and uses its get methods to return the data for the object into a string variable. To return the title and price for the order, the code first calls the getBook method, which returns a Book object, then calls the getTitle and getPrice methods from that object. After all of the data has been returned to the string, the string is displayed in a dialog box.
Now that you've seen how inheritance works, you can ask whether using it makes sense in a case like this. A simple alternative, for example, is to provide for discounts in the BookOrder class itself. To do that, you could add a third parameter to the constructor and adjust the code as needed. Or, you could add a second constructor to that class with a third parameter for the key code. Either way, the coding for the book order application would be simplified.....