# class KeyMaster {
# public int i;
# public KeyMaster(int i) {
# this.i = i;
# }
# public boolean equals(Object o) {
# return i == ((KeyMaster) o).i;
# } 这里 (KeyMaster) o 为什么要把o强制转换成 Object类型?谁帮忙解释下,在什么地方需要用到类似的强制转换~ 谢谢
# public int i;
# public KeyMaster(int i) {
# this.i = i;
# }
# public boolean equals(Object o) {
# return i == ((KeyMaster) o).i;
# } 这里 (KeyMaster) o 为什么要把o强制转换成 Object类型?谁帮忙解释下,在什么地方需要用到类似的强制转换~ 谢谢
# return i == ((KeyMaster) o).i; // 转换成真正的类型后再进行比较操作.
# } 面向对象的内容, 可以再好好看看.
# return i == ((KeyMaster) o).i;
# }
你如果换成这样的话
# public boolean equals(KeyMaster o) {
# return i == o.i;
# }
这样也行的,就是传进来的变量一定要是KeyMaster这个类的对象
因为equals是KeyMaster从Object继承下来的(所有类默认继承于Object);
现在要重写(override)这个方法,就需要一致的函数签名(返回类型可以协同);
如果不做转换的话,Object o这个对象是没有i字段的。
public int i;
public KeyMaster(int i) {
this.i = i;
}
// 在这里你把Object类的equals方法重写(覆盖)了,因为你写的equals方法和Object类的equals方法的参数集, 返回值,函数名字相等。
public boolean equals(Object o) {
// 因为你的类KeyMaster 隐式的继承了Object类,所以可以强行转化为KeyMaster类
// 因为参数是Object类型的,但是Object类里没有i这个成员变量,所以必须强制转化为KeyMaster类才能使用这个变量i,不然编译出错!
return i == ((KeyMaster) o).i;
} 可以看成以下代码!class KeyMaster extends Object {
public int i;
public KeyMaster(int i) {
this.i = i;
}
public boolean equals(Object o) {
return i == ((KeyMaster) o).i;
}