Abstract Methods and Classes

时间:2022-08-15 10:43:46

阅读了Java的官方Doc,在此总结如下。

Abstract Class & Method

In jave, "abstract" can be a modifier to class and method.

Abstract class:

A class that is declared abstract—it may or may not include abstract methods.

Abstract classes cannot be instantiated, but they can be subclassed.

Abstract method:

a method that is declared without an implementation (without braces, and followed by a semicolon), like this:

abstract void moveTo(double deltaX, double deltaY);

Relationship:

If a class includes abstract methods, then the class itself must be declared abstract.

If subclass of an abstract class does not implement all of the abstract methods, then the subclass must also be declared abstract.

Abstract Class vs Interface

Same:

Cannot be inistantiated.

Difference:

1. 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.

2. You can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.

3. A class that implements an interface must implement all of the interface's methods.

When to use Abstract Class:

1. You want to share code among several closely related classes.
2. 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).
3. 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.

When to use Interface:

1. You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
2. You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
3. You want to take advantage of multiple inheritance of type.