chapter_12_beginning_javabook

Inheritance is one of the key concepts in object

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: e existing class. Inheritance is one of the key concepts in object-oriented programming. With inheritance it is possible to derive a new class from an existing class. Inheritance extends an existing class and produces a new class. If a source program contains a class declaration that begins class UpperClass { ... it is possible to write later in the same program or in some other program file class LowerClass { ... extends UpperClass The latter declaration specifies that class LowerClass inherits class UpperClass. The keyword extends tells the compiler that the members (fields and methods) of class UpperClass must be inherited to LowerClass. Those members that are declared with access modifiers (keywords) public or protected in UpperClass become similar members in LowerClass. Those members that are declared without access modifiers in UpperClass become similar members in LowerClass provided that the classes belong to the same package of classes. In the discussion above, the classes are named UpperClass and LowerClass. These names are chosen to indicate the fact that a class that inherits another class is on a lower level. It can exist only after the upper-level class has been declared. In the terminology of object-oriented programming, we say that UpperClass is a superclass or base class of LowerClass, LowerClass is a subclass of UpperClass, and LowerClass is derived from UpperClass. When a class inherits another class, the classes form a class hierarchy. The class that inherits is in a lower position in the hierarchy. Later on, we shall see that there can be more than just two classes in a class hierarchy. Program BetterDate.java is an example where inheritance is used to derive a new class from class Date. The name of the derived class is BetterDate. Although the declaration of class BetterDate fits on a single page, BetterDate contains practically everything that is in class Date that needs ten pages to be described. The derived class BetterDate contains all fields of class Date, all methods excluding the constructors of class Date, its own constructor, and its own two methods to_string_with_month_name() and to_american_format_string(). It must be noted that a derived class needs, in most cases, a constructor of its own. Constructors are not inherited from the upper class. 12.1 Base classes and derived classes 385 Class BetterDate is better than class Date because it has two ne...
View Full Document

This document was uploaded on 01/20/2014.

Ask a homework question - tutors are online