Java: interface vs abstract class (about fields)

From the content I collected, I want to force a class to use specific private fields (and methods). I need an abstract class because an interface only declares public / static / final fields and methods correct??

I just started my first big java project and wanted to make sure I wouldn't hurt myself later:)

Solution

It is common to provide both, so the final result is:

public interface Sendable {
    public void sendMe();
}

and

public abstract class AbstractSender implements Sendable {
    public abstract void send();

    public void sendMe() {
        send(this.toString());
    }
}

In this way, anyone who is satisfied with the default implementation in the abstract class can subclass it quickly without rewriting a lot of code, but anyone who needs to do more complex things (or inherit from different base classes) can still implement the interface and plug and play

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
分享
二维码
< <上一篇
下一篇>>