gpt4 book ai didi

java - 普通接口(interface)类和只有抽象方法的抽象类有什么区别吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:23 25 4
gpt4 key购买 nike

我只是好奇他们的待遇是否有所不同。

例如,如果我们有:

界面:

public interface Test {
public void method();
}

和抽象类:

public abstract class Test {
public abstract void method();
}

JVM 会以不同方式对待这些类吗?两者中哪一个在存储期间占用更多磁盘空间,哪个将使用最多的运行时内存哪个执行更多操作(性能更好 ).

这个问题不是关于何时使用接口(interface)或抽象类。

最佳答案

Yes, they are different.

With an interface, clients could implement it aswell as extend a class:

class ClientType implements YourInterface, SomeOtherInterface { //can still extend other types

}

With a class, clients will be able to extend it, but not extend any other type:

class ClientType extends YourClass { //can no longer extend other types

}

Another difference arises when the interface or abstract class have only a single abstract method declaration, and it has to do with anonymous functions (lambdas).

As @AlexanderPetrov said, an interface with one method can be used as a functional interface, allowing us to create functions "on-the-fly"where ever a functional interface type is specified:

//the interface
interface Runnable {
void run()
}

//where it's specified
void execute(Runnable runnable) {
runnable.run();
}

//specifying argument using lambda
execute(() -> /* code here */);

This cannot be done with an abstract class.So you cannot use them interchangably. The difference comes in the limitations of how a client can use it, which is enforced by the semantics of the JVM.

As for differences in resource usage, it's not something to worry about unless it's causing your software problems. The idea of using a memory-managed language is to not worry about such things unless you are having problems. Don't preoptimize, I'm sure the difference is negligable. And even if there is a difference, it should only matter if it may cause a problem for your software.

If your software is having resource problems, profile your application. If it does cause memory issues, you will be able to see it, as well as how much resources each one consumes. Until then, you shouldn't worry about it. You should prefer the feature that makes your code easier to manage, as opposed to which consumes the least amount of resources.

关于java - 普通接口(interface)类和只有抽象方法的抽象类有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38488736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com