Java: Interface vs Abstract Class (regarding field

2020-05-19 08:07发布

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 :)

11条回答
够拽才男人
2楼-- · 2020-05-19 08:26

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.

查看更多
爷、活的狠高调
3楼-- · 2020-05-19 08:29

If you want a class to use certain fields or methods of another class, you could declare them as protected.

    public abstract class A {

      protected Object thing;
    }

can be accessed by another class in the same package (could be extending class A, or not)

A a = new A();
a.thing.toString();

It's not really "forcing" another class to use it though, more like "enabling".

查看更多
劫难
4楼-- · 2020-05-19 08:30

Private fields and methods cannot be used by subclasses (except if they are also inner classes). You could make them protected, however.

查看更多
孤傲高冷的网名
5楼-- · 2020-05-19 08:30

If you ever find yourself guessing which one to choose I's suggest to err on the side of Interfaces - It's better to have an interface that should have been an abstract class than the other way around.

查看更多
我命由我不由天
6楼-- · 2020-05-19 08:30

This is correct. But it is not necessarily an either-or decision, you can combine the advantages of interfaces and abstract classes by providing a skeletal implementation along with your interface. You can find a very interesting description of this approach in Effective Java, 2nd Ed., Item 18 ("Prefer interfaces to abstract classes").

查看更多
对你真心纯属浪费
7楼-- · 2020-05-19 08:33
I want to force a class to use particular private fields (and methods)

This part of your question is questionable: why do you think you want to do this?

private members are not visible to subclasses, and interfaces define the public interface, so your only choice would be to use an abstract class...but I cannot think of any reason why anyone would ever want to do this

查看更多
登录 后发表回答