Java:接口与抽象类(关于字段) [英] Java: Interface vs Abstract Class (regarding fields)
问题描述
从我收集的内容来看,我想强制一个类使用特定的私有字段(和方法)我需要一个抽象类,因为接口只声明public / static / final字段和方法。正确??
我刚刚开始了我的第一个大型java项目,并希望确保我以后不会伤害自己:)
提供这两者是相当普遍的,所以你最终得到:
public interface Sendable {
public void sendMe();
}
和
公共抽象类AbstractSender实现Sendable {
public abstract void send();
public void sendMe(){
send(this.toString());
}
}
这样,任何对默认实施感到满意的人在抽象类中可以快速子类化它而无需重写大量代码,但是任何需要做更复杂事情(或者需要从不同基类继承)的人仍然可以实现接口并且即插即用。 / p>
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??
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();
}
and
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屋!