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

That's correct. Interfaces are for public consumption. And private implementation needs to be in an abstract (or concrete) class.

查看更多
Explosion°爆炸
3楼-- · 2020-05-19 08:46

An interface defines just that - an interface (contract) with the world outside the implementing class. The public methods of a (abstract or not) superclass do the same. You shouldn't try to require subclasses to have certain private members - you are trying to specify implementation which is what OOP is all about avoiding.

You use an abstract class when you want to define some shared behaviour in a superclass - but that class can't stand on its own (it needs to be subclassed). It may be that the shared behaviour needs some state of its own - in which case it can define private fields, and it may also have private methods which only it can use.

Even if you inherit from an abstract class, you won't be able to access its private fields/methods.

查看更多
放荡不羁爱自由
4楼-- · 2020-05-19 08:47

You don’t want to force the use of certain private fields or methods. In general you don’t care about the implementation, you care about the interface. So define a couple of methods in a couple of interfaces (depending on how much you need) and define classes that implement them. This will probably hurt you the least in the future.

查看更多
\"骚年 ilove
5楼-- · 2020-05-19 08:49

Interfaces define a contract for behavior. That's what they need to be about, not attributes.

查看更多
萌系小妹纸
6楼-- · 2020-05-19 08:53

If you want the subclass to define specific methods, using an interface will do the trick. As others have said, it's not so much about how the subclass does it, just the fact that it will do it.

查看更多
登录 后发表回答