[英]Overriding equals method by a abstract class and set it as abstract so if any class extends, they must implement
I'm trying to build an abstract class/interface that overrides methods that already exist and set them as abstract. 我正在尝试构建一个抽象类/接口来覆盖已经存在的方法,并将它们设置为抽象方法。 Is this possible?
这可能吗?
Code example: 代码示例:
public abstract class Box {
@Override
public abstract boolean equals(Object o);
}
OR 要么
public interface Box {
@Override
boolean equals(Object o);
}
Both of the class and interfaces above should have the same function, but does this mean both override Object equals method? 上面的类和接口都应该具有相同的功能,但这是否意味着这两个对象都覆盖了equals方法? even if I set it as abstract?
即使我将其设置为抽象?
So will this work: 所以这项工作:
public class Tea extends Box {
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
return false;
}
}
First off, interfaces do not override methods. 首先,接口不会覆盖方法。 So you cannot override
equals
from Object
by adding an equals
method to an interface. 因此,您不能通过向接口添加
equals
方法来从Object
覆盖equals
。 Interfaces instead can be thought of as contracts, they guarantee that any non-abstract class implementing them will have all of the interfaces methods (either directly or through inheritance). 相反,可以将接口视为契约,它们保证实现它们的任何非抽象类都将具有所有接口方法(直接或通过继承)。
In regards to making a method abstract through inheritance, you can in fact do this. 关于通过继承使方法抽象的方法,实际上可以做到这一点。 So your example of overriding the
equals
method with an abstract definition in your abstract Box class will cause any classes extending Box
to have to implement an equals
method. 因此,您在抽象Box类中使用抽象定义覆盖
equals
方法的示例将导致扩展Box
任何类都必须实现equals
方法。
And as @OskarEmilsson commented, if you do this then you should also force hashCode
to be implemented since equals and hashCode should be consistent with each other (equals objects must have equal hashCodes). 就像@OskarEmilsson所评论的那样,如果您这样做,则还应该强制执行
hashCode
,因为equals和hashCode应该彼此一致(相等的对象必须具有相等的hashCodes)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.