Java抽象类和接口

Java抽象类和接口

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

问题描述

在采访中我被问到以下问题。



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



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



解决方案

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



JRE中的例子: LinkedList 列表 Deque 。这些接口定义了类的行为。它们不提供任何实现细节。虽然抽象类可以提供



相关问题:和。后者不直接相关,但它显示了为什么需要接口,即使在一个抽象类足够的情况下。


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

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.

Can anyone explain me in brief.

解决方案

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

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.

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抽象类和接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:43