何时使用抽象类和接口? [英] When to use Abstract Classes and Interfaces?

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

问题描述

为什么我们使用Interface?

Why we use Interface?

当我们实现一个接口时,我们必须为该接口的方法编写定义。
那么,实现接口需要什么?我们可以直接在类中编写方法。

When we implement one interface we have to write definition for methods of that interface. So, what is need to implement interface? We can directly write methods in the class.

谢谢:)

推荐答案

一个示例可能对您有用,请参阅下面的场景。

an example might be useful for you,see below scenarios.

1.class A extends B{
..
..
..
}

当A扩展B并且你正在创建一个新的C类时,你无法制作扩展C和B So 转到接口。

when A extends B and you are creating A new class C ,you can not make A extend C along with B So go for Interface.

2.class A implements B {
..
..
}

如果在B中添加一个新方法并且它(B)由100个类实现,则很难在所有类中实现新方法,因此去抽象类并添加具有框架实现的新方法。

If you add a new method in B and it(B) is implemented by 100 classes ,it is hard to implement new method in all classes,so go for abstract class and add new method with skeleton implementation.

进一步的帮助阅读 Effective Java 作者:Joshua Bloch。

for further help read Effective Java by Joshua Bloch.

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

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