引用类

 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 (父类的成员变量)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值