何时以及为何使用抽象类/方法? [英] When and Why to use abstract classes/methods?

查看:94
本文介绍了何时以及为何使用抽象类/方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对抽象类/方法有一些基本问题,我知道抽象类的基本用途是为将来的类创建模板。但是它们还有更多用途吗?与接口相比,什么时候应该首选它们?还有什么时候抽象方法有用?

I have some basic questions about abstract classes/methods.I know basic use of abstract classes is to create templates for future classes. But are there any more uses of them ? When should you prefer them over interfaces and when not ? Also when are abstract methods useful ?

推荐答案


我知道抽象类
的基本用法是为将来的$创建模板b $ b类。但是其中还有
个用途吗?

I know basic use of abstract classes is to create templates for future classes. But are there any more uses of them?

不仅可以为孩子定义模板,还可以为Abstract Classes提供模板让您定义子类以后可以使用的功能的额外好处。

Not only can you define a template for children, but Abstract Classes offer the added benefit of letting you define functionality that your child classes can utilize later.

您无法在Java 8之前的接口中提供默认方法实现。

You could not provide a default method implementation in an Interface prior to Java 8.


您何时应该在
接口上使用它们?何时不该使用它们呢?

When should you prefer them over interfaces and when not?

如果需要,抽象类非常合适为孩子提供实现细节,但又不想直接实例化您的类的实例(允许您部分定义一个类)。

Abstract Classes are a good fit if you want to provide implementation details to your children but don't want to allow an instance of your class to be directly instantiated (which allows you to partially define a class).

如果您想简单地定义要遵循的对象合同,则可以使用接口。

If you want to simply define a contract for Objects to follow, then use an Interface.


抽象方法什么时候有用?

Also when are abstract methods useful?

抽象方法的使用方式与在接口中定义方法的方式相同有用。这是Abstract类的设计人员说我的任何孩子都必须实现此方法的一种方式。

Abstract methods are useful in the same way that defining methods in an Interface is useful. It's a way for the designer of the Abstract class to say "any child of mine MUST implement this method".

这篇关于何时以及为何使用抽象类/方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆