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 abstract method is automatically abstract itself and must be declared as such.

  • An abstract class cannot be instantiated.

  • A subclass of an abstract class can be instantiated only if it overrides each of the abstract methods of its superclass and provides ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.