非静态内部类为什么可以访问外部类的静态成员

非静态内部类对象寄生于外部类对象,inn调用test()方法时,知道自己调用的是它寄生的对象所属类的类成员;

在阶段一:类加载的时候没有创建外部类对象,但是方法是知道要调用的是外部类的类成员,已经确定了

在第二阶段:创建非静态内部类对象,该对象必须寄生于外部类对象,它知道要调用自己寄生的这个对象所属的类的类方法,也是确定的

public class TestOutInn {


public static void main(String[] args) {
OutA out=new OutA();
OutA.InnA inn=out.new InnA();//inn 寄生于out,没有out一定没有inn
inn.test();//方法是用来被调用的,当inn调用test方法时,它知道f(),a都属于谁,所以底层跑的时候很清楚
OutA.InnB innb=new OutA.InnB();//从创建内部类的方式就可以看出innb是属于类的
innb.show();//底层不知道是哪个对象的weight值,会报异常
}


}
class OutA{
int weight;
private static int a=8;
private static void f(){
System.out.println("外部类静态方法");
}
class InnA{

public void test(){

/**
* 如果内部类的变量名和外部类的变量名相同,要注意区分

*/
int a=10000;
System.out.println(a);//默认是this的a
System.out.println(OutA.a);//在这里要写成(OutA.a)
System.out.println(this.a);//在这里调用的是非静态内部类对象的a
f();
}
}
static class InnB{
public void show(){
System.out.println(weight);
}
}
}
/*
 * 在java中运行的结果是:
 * 10000
 * 8
 * 10000
 * 外部类静态方法
 * Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 * Cannot make a static reference to the non-static field weight
 *
 * at cn.zhishidian.ying.OutA$InnB.show(TestOutInn.java:29)
 * at cn.zhishidian.ying.TestOutInn.main(TestOutInn.java:10)

*/

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值