java内子类的重写方法里面,使用了该方法,那么被使用的方法是父类的还是子类的呢。。
自己写了一个类来测试,结果是使用子类自己的方法;而看视频的内容好像是使用了父类的方法,并且eclipse悬停时指示的也是。两个代码如下:
自己的:
public class Test1 {
public int changeTo99(int[] i){
i[0] = 99;
return i[0];
}
public int changeTo100(int[] i){
i[0] = 100;
return i[0];
}
}
public class Test2 extends Test1{
public int changeTo100(int[] i){
if(i[0] == 0) i[0] = 7;
else {
changeTo100(i);
}
return i[0];
}
public static void main(String[] args) {
Test2 t = new Test2();
int[] i = {1,2,3};
t.changeTo100(i);
System.out.println(i[0]);
}
}
上课看到的:
public class SList {
private SListNode head;
private int size;
private SListNode tail;
//other codes
public boolean equals(Object other) {
if (!(other instanceof SList)) { // Reject non-SLists.
return false;
}
SList o = (SList) other;
if (size != o.size) {
return false;
}
SListNode n1 = head;
SListNode n2 = o.head;
while (n1 != null) {
if (!n1.item.equals(n2.item)) { // Deep equality of the items.
return false;
}
n1 = n1.next;
n2 = n2.next;
}
return true;
}
}
后者使用的equals是重写了Object内的equals,然后方法内还用了一个equals,可是这个使用的equals是仍然是Object的。。。而自己写的两个Test类就不是这样,Test2中重写的changeTo100里面用的是Test2自己的。这样很奇怪啊。。。。。。求教!