Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

java - Force a class to override the .equals method

I have a bunch of class who implement a common interface : Command.

And this bunch of class goes to a Map.

To get the Map working correctly, I need to each class who implements Command to override the Object.equals(Object other) method.

it's fine.

But i whould like to force the overriding of equals. => Have a compilation error when something who implement command dont override equals.

It's that possible ?

Edit : BTW , i will also need to forcing the override of hashcode...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No, you can't. What you can do, however, is use an abstract base class instead of an interface, and make equals() abstract:

abstract class Command {
   // put other methods from Command interface here

   public abstract boolean equals(Object other);
   public abstract int hashCode();
}

Subclasses of Command must then provide their own equals and hashCode methods.

It's generally bad practice to force API users to extend a base class but it may be justified in this case. Also, if you make Command an abstract base class instead of an interface, rather than introducing an artificial base class in addition to the Command interface, then there's no risk of your API users getting it wrong.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...