Abstract Methods and Classes

阅读了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.

 

转载于:https://www.cnblogs.com/ireneyanglan/p/4949574.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值