Abstract Methods and Classes
An abstract class is a class that is declared
abstract
—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, then the class itself must be declared
abstract
, as in:public abstract class GraphicObject { // declare fields // declare nonabstract methods abstract void draw(); }
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared
abstract
.Note: Methods in an interface (see the Interfaces section) that are not declared as default or static are implicitly abstract, so the
abstract
modifier is not used with interface methods. (It can be used, but it is unnecessary.)Abstract Classes vs Interfaces
- Abstract classes are similar to interfaces.
- You cannot instantiate them
- Both may contain a mix of methods declared with or without an implementation.
- However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
- With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public.
- In addition, you can extend only one class, whether or not it is abstract,
- You can implement any number of interfaces.
Which should you use, abstract classes or interfaces?
- Consider using abstract classes if any of these statements apply to your situation:
- You want to share code among several closely related classes.
- You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
- You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.
- Consider using interfaces if any of these statements apply to your situation:
- You expect that unrelated classes would implement your interface. For example, the interfaces
Comparable
andCloneable
are implemented by many unrelated classes. - You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
- You want to take advantage of multiple inheritance of type.
- You expect that unrelated classes would implement your interface. For example, the interfaces
No comments:
Post a Comment