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

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

问题描述

我有一些关于抽象类/方法的基本问题.我知道抽象类的基本用途是为未来的类创建模板.但是它们还有其他用途吗?什么时候应该比接口更喜欢它们,什么时候不呢?另外,抽象方法什么时候有用?

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

推荐答案

我知道抽象类的基本用法是为未来创建模板类.但是还有没有更多的用途其中?

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

您不仅可以为子类定义模板,抽象类还提供了额外的好处,让您可以定义子类以后可以使用的功能.

Not only can you define a template for children, but Abstract Classes offer the added benefit of letting you define the 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 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天全站免登陆