Abstract Classes and Methods
In Example 3-4,
we declared our
Circle class to be part of a package named
shapes. Suppose we plan to implement a number of
shape classes: Rectangle,
Square, Ellipse,
Triangle, and so on. We can give these shape
classes our two basic area( ) and
circumference() methods. Now, to make it easy to
work with an array of shapes, it would be helpful if all our shape
classes had a common superclass, Shape. If we
structure our class hierarchy this way, every shape object,
regardless of the actual type of shape it represents, can be assigned
to variables, fields, or array elements of type
Shape. We want the Shape class
to encapsulate whatever features all our shapes have in common (e.g.,
the area() and circumference( )
methods). But our generic Shape class
doesn’t represent any real kind of shape, so it
cannot define useful implementations of the methods. Java handles
this situation with abstract methods.
Java
lets us define a method without implementing it by declaring the
method with the abstract modifier. An
abstract method has no body; it simply has a
signature definition followed by a semicolon.[8]
Here are the rules about abstract methods and the
abstract classes that contain them:
Any class with an
abstractmethod is automaticallyabstractitself and must be declared as such.An
abstractclass cannot be instantiated.A subclass of an
abstractclass can be instantiated only if it overrides each of theabstractmethods of its superclass and provides ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access