Is it possible to force a class to implement a Java attribute?

Asked

Viewed 117 times

1

It is possible to force a class to implement an attribute in Java?

I know that through interfaces you can force the class to implement methods, but I would like to do this with attributes as well.

Or if it is not possible to force the class to have the attribute, at least display a Warn in the IDE warning that that attribute should be implemented the same as when we implement the interface Serializable, where the IDE is giving Warning until we implement the serialVersionUID;

  • Cite the real example ... a minimal example...

  • I created an interface called Indentifiable, this interface has getId() and setId() methods that require the implementation of these methods, but I also wanted to put the ID field to force to also have it.

1 answer

3


What are you calling attribute is actually called field. I understand you learned that way because there’s too much wrong material.

A private field is implementation detail and so only the type who needs it should have your knowledge. Not being public has no reason to force do anything, it is the decision of the implementor to use or not a private field to get the desired result. Interfaces can’t say anything about the private part of a class.

If you’re talking about a public field can’t because interfaces are only about behaviors (at least their contract). It even has technical implications that make it difficult enough to do so. And should it have a public field?

If you really want to force a contract that has a certain data you can put on the interface a method getter and another probably Setter which in theory would require the implementer to create the desired private field. Nothing prevents the class from enabling the necessary behavior that the interface requires otherwise, but in some cases it cannot be otherwise. This may slightly misrepresent the purpose of the object, but if the definition of the problem really requires this exposed data, then it is a good solution. I just think that many times the definition of the problem is wrong.

Create a getter/Setter could be abuse.

You can create an addendum to the IDE that tells you this by analyzing your code, but it’s not usually beneficial. There seems to be a misconception of how to use the interface, so it would probably be a mistake to do something like this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.