Java Reference
In-Depth Information
BankAccount anAccount; //
OK
anAccount = new BankAccount(); //
ErrorȌ
BankAccount
is
abstract
anAccount = new SavingsAccount(); //
OK
anAccount = null; //
OK
The reason for using abstract classes is to force programmers to create subclasses.
By specifying certain methods as abstract, you avoid the trouble of coming up with
useless default methods that others might inherit by accident.
Abstract classes differ from interfaces in an important wayȌthey can have
instance fields, and they can have concrete methods and constructors.
A
DVANCED
T
OPIC
10.2: Final Methods and Classes
In
Advanced Topic 10.1
you saw how you can force other programmers to create
subclasses of abstract classes and override abstract methods. Occasionally, you
may want to do the opposite and prevent other programmers from creating
subclasses or from overriding certain methods. In these situations, you use the
final
keyword. For example, the
String
class in the standard Java library has
been declared as
public final class String { . . . }
That means that nobody can extend the
String
class.
The
String
class is meant to be immutableȌstring objects can't be modified by
any of their methods. Since the Java language does not enforce this, the class
designers did. Nobody can create subclasses of
String
; therefore, you know that
all
String
references can be copied without the risk of mutation.
You can also declare individual methods as final:
public class SecureAccount extends BankAccount
{
. . .
public final boolean checkPassword(String
password)
{
. . .