java抽象类和接口有什么区别,Java 8中的抽象类和接口有什么区别?

Java 8 引入了接口的默认实现,模糊了抽象类和接口之间的关键差异。现在,主要区别在于抽象类遵循传统的单继承,而接口支持多重继承。这引发了一个问题:Java 8 如何解决钻石问题?当接口中有冲突的默认方法时,编译器会发出警告,需要显式选择实现。示例代码展示了如何通过重写接口方法来解决这个问题。此外,接口不能包含状态,而抽象类可以,这也是它们的一个重要区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

In Java there used to be a subtle but important difference between abstract classes and interfaces: default implementations. Abstract classes could have them, interfaces could not. Java 8 though introduces default implementations for interfaces, meaning this is no longer the critical difference between an interface and an abstract class.

So what is?

As best as I can tell, the only remaining difference (besides perhaps some under the hood efficiency stuff) is that abstract classes follow traditional Java single-inheritance, whereas interfaces can have multiple-inheritance (or multiple-implementation if you will). This leads me to another question -

How do the new Java 8 interfaces avoid the diamond Problem?

解决方案

Interfaces cannot have state associated with them.

Abstract classes can have state associated with them.

Furthermore, default methods in interfaces need not be implemented. So in this way, it will not break already existing code, as while the interface does receive an update, the implementing class does not need to implement it.

As a result you may get suboptimal code, but if you want to have more optimal code, then your job is to override the default implementation.

And lastly, in case a diamond problem occurs, then the compiler will warn you, and you will need to choose which interface you want to implement.

To show more about the diamond problem, consider the following code:

interface A {

void method();

}

interface B extends A {

@Override

default void method() {

System.out.println("B");

}

}

interface C extends A {

@Override

default void method() {

System.out.println("C");

}

}

interface D extends B, C {

}

Here I get the compiler error on interface D extends B, C, that:

interface D inherits unrelated defaults for method() form types B and C

The fix is:

interface D extends B, C {

@Override

default void method() {

B.super.method();

}

}

In case I wanted to inherit the method() from B.

The same holds for if D were a class.

To show even more about the difference between interfaces and abstract classes in Java 8, consider the following Team:

interface Player {

}

interface Team {

void addPlayer(Player player);

}

You can in theory provide a default implementation of addPlayer such that you can add players to for example a list of players.

But wait...?

How do I store the list of players?

The answer is that you cannot do that in an interface, even if you have default implementations available.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值