Java Reference
In-Depth Information
5.
Which instance field will we need to add to the
CheckingAccount
class?
10.3 Inheriting Instance Fields and Methods
When you form a subclass of a given class, you can specify additional instance fields
and methods. In this section we will discuss this process in detail.
When defining the methods for a subclass, there are three possibilities.
1. You can override methods from the superclass. If you specify a method with
the same signature (that is, the same name and the same parameter types), it
overrides the method of the same name in the superclass. Whenever the method
is applied to an object of the subclass type, the overriding method, and not the
original method, is executed. For example,
CheckingAccount.deposit
overrides
BankAccount.deposit
.
2. You can inherit methods from the superclass. If you do not explicitly override a
superclass method, you automatically inherit it. The superclass method can be
applied to the subclass objects. For example, the
SavingsAccount
class
inherits the
BankAccount.getBalance
method.
3. You can define new methods. If you define a method that did not exist in the
superclass, then the new method can be applied only to subclass objects. For
example,
SavingsAccount.addInterest
is a new method that does not
exist in the superclass
BankAccount
.
445
446
The situation for instance fields is quite different. You can never override instance
fields. For fields in a subclass, there are only two cases:
1. The subclass inherits all fields from the superclass. All instance fields from the
superclass are automatically inherited. For example, all subclasses of the
BankAccount
class inherit the instance field
balance
.
2. Any new instance fields that you define in the subclass are present only in
subclass objects. For example, the subclass
SavingsAccount
defines a new
instance field
interestRate
.