Java – what is the difference between a normal interface class and an abstract class with only abstract methods?

I'm just curious if they have any different treatment

For example, if we have:

Interface:

public interface Test {
    public void method();
}

Abstract classes:

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

Will the JVM handle these classes differently? Which of these two takes up more disk space during storage, which will exhaust the most runtime memory, and which will perform more operations (better performance)

This question is not about when to use interfaces or abstract classes

Solution

Yes, they are different

Through the interface, the client can implement it and extension classes:

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

}

Using the class, the client will be able to extend it without extending any other types:

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

}

Another difference occurs when an interface or abstract class has only one abstract method declaration, which is related to anonymous functions (Lambdas)

As @ Alexander Petrov said, an interface with a method can be used as a function interface, allowing us to create a function "in operation", in which the function 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 abstract classes So you can't use them interchangeably The difference is the limitation of how the client uses it, which is enforced by the semantics of the JVM

As for the difference in resource use, don't worry unless it causes your software problems The idea of using a memory management language is not to worry about these things unless you encounter problems Don't optimize in advance. I'm sure the difference can be ignored Even if there is a difference, it should be important whether it may cause problems with your software

If your software has resource problems, please analyze your application If it does cause memory problems, you will be able to see it and the amount of resources consumed by each You shouldn't worry about it until then You should prefer features that make your code easier to manage rather than consuming minimal resources

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>