class Base{
static int i=2;
public void show(){
System.out.println("the value of i ="+i);
}
}
class Test extend Base{
static int i=3;
public static void main(String args[]){
Base b=new Test();
b.show();
}
public void show(){
System.out.println("the value of i ="+i);
}
}
输出的是:the value of i =3
当Test中没有 show的时候,结果为:
the value of i =2
因为之类的功能比父类强大.父类的对象指向之类的引用时 父类中的方法被之类重写过了.所以你调用父类中的方法时实际上是调用重写后的方法了.
class Base {
int x=3;
public Base() {}
public void show() {
System.out.print(" The value is " + x);
}
}
class Derived extends Base {
int x=2;
public Derived() {}
public void show() {
System.out.println(" The value is " + x);
}
}
public class Test {
public static void main(String args[]) {
Base b = new Derived();
b.show();
System.out.println("The value is " +b.x);
}
}
答案是:the value of i =2
the value of i =3
题主要考的是引用的范围——Base b = new Derived();
父类引用变量b引用子类Derived子类的对象,这样的情形会限制引用的范围
b的引用范围是:继承自父类的成员+被覆盖的成员。
明白上面的公理后,就不难得出答案:the value of i =2 (被覆盖的成员方法)
the value of i =3 (父类的成员变量)
本文通过具体的Java代码示例,展示了如何在继承结构中实现方法的重写,并解释了父类引用指向子类对象时的行为特点,有助于理解Java中继承与多态的概念。
2183

被折叠的 条评论
为什么被折叠?



