Java抽象类和接口 [英] Java abstract class and interface

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

问题描述

在面试中,我被问到以下问题.我试图回答这个问题,但我想要这个问题的确切答案.

In interview I have been asked following question. I tried to answer the question but I want exact answer of the question.

如果我可以将抽象类模拟为接口,为什么java提供接口?

If I can simulate Abstract class as Interface, why java provided Interface?

这意味着如果在抽象类中我可以将所有方法标记为抽象,然后抽象类将作为接口工作,那么为什么我需要接口.

This mean if in Abstract class I can mark all methods as abstract and then abstract class will work as interface, so why I need interface.

谁能简单解释一下.

推荐答案

这是一个非常标准的面试问题.答案是:因为你可以实现多个接口,但不能扩展多个抽象类.

That's a very standard interview question. The answer is: because you can implement multiple interfaces, but can't extend multiple abstract classes.

来自 JRE 的示例:LinkedList 既是 List 又是 Deque.这些接口定义了类的行为.它们不提供任何实现细节.而抽象类可以提供一些.

Example from the JRE: LinkedList is both a List and a Deque. These interfaces define the behaviour of the class. They do not provide any implementation details. While abstract classes could provide some.

相关问题:this这个.后者没有直接关系,但它说明了为什么需要接口,即使在抽象类就足够的情况下也是如此.

Related questions: this and this. The latter is not directly related, but it shows why are interfaces needed, even in cases when an abstract class would suffice.

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

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