Java:接口与抽象类(关于字段) [英] Java: Interface vs Abstract Class (regarding fields)
问题描述
从我收集到的信息来看,我想强制一个类使用特定的私有字段(和方法) 我需要一个抽象类,因为接口只声明了 public/static/final 字段和方法.正确吗??
From what I have gathered, I want to force a class to use particular private fields (and methods) I need an abstract class because an interface only declares public/static/final fields and methods. Correct??
我刚刚开始了我的第一个大型 Java 项目,并希望确保以后不会伤害自己 :)
I just started my first big java project and want to make sure I'm not going to hurt myself later :)
推荐答案
两者都提供是很常见的,所以你最终会得到:
It's fairly common to provide both, so that you end up with:
public interface Sendable {
public void sendMe();
}
和
public abstract class AbstractSender implements Sendable {
public abstract void send();
public void sendMe() {
send(this.toString());
}
}
这样,任何对抽象类中的默认实现感到满意的人都可以快速子类化,而无需重写大量代码,但是任何需要做更复杂的事情(或需要从不同的基类继承)的人仍然可以实现接口,即插即用.
That way, anyone who is happy with the default implementation in the abstract class can quickly subclass it without rewriting a lot of code, but anyone who needs to do something more complex (or who needs to inherit from a different base class) can still implement the interface and be plug-and-play.
这篇关于Java:接口与抽象类(关于字段)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!