【发布时间】:2014-09-14 06:13:28
【问题描述】:
我对下面的静态绑定示例感到困惑。我认为S2.x 和S2.y 显示静态绑定,因为它们根据s2 的静态类型打印出字段。并且S2.foo() 使s2 在超类中调用foo 方法,因为foo 在子类中没有被覆盖。
但是对于S2.goo(),它不应该调用Test1 子类中的goo() 方法吗?就像它的多态性?怎么会是静态绑定?看起来S2.goo() 调用了超类goo() 方法并打印出=13。非常感谢您提前提供的帮助!
public class SuperClass {
public int x = 10;
static int y = 10;
protected SuperClass() {
x = y++;
}
public int foo() {
return x;
}
public static int goo() {
return y;
}
}
和子类
public class Test1 extends SuperClass {
static int x = 15;
static int y = 15;
int x2= 20;
static int y2 = 20;
Test1()
{
x2 = y2++;
}
public int foo2() {
return x2;
}
public static int goo2() {
return y2;
}
public static int goo(){
return y2;
}
public static void main(String[] args) {
SuperClass s1 = new SuperClass();
SuperClass s2 = new Test1();
Test1 t1 = new Test1();
System.out.println("S2.x = " + s2.x);
System.out.println("S2.y = " + s2.y);
System.out.println("S2.foo() = " + s2.foo());
System.out.println("S2.goo() = " + s2.goo());
}
}
【问题讨论】:
标签: java inheritance binding static polymorphism