A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© U芽Lady 中级黑马   /  2013-4-18 11:00  /  1740 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 U芽Lady 于 2013-4-19 07:08 编辑

class Out{
int x = 1;
class In{
  int x = 2;
  public void show(){
   System.out.println(Out.x);
  }
}
}
class Demo {
public static void main(String[] args) {
  Out.In o = new Out().new In();
  o.show();
}
}


---------- javac ----------
Demo.java:6: 错误: 无法从静态上下文中引用非静态 变量 x
   System.out.println(Out.x);
                         ^
1 个错误
输出完成 (耗时 1 秒) - 正常终止

为什么报这样的错呢,不是内部类可以直接应用外部的成员吗???

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

3 个回复

倒序浏览
内部类你可以把他当成是一个成员,既然是在成员位置上,你仔细想想看,老毕是不是讲过,静态成员不能访问非静态成员,非静态成员可以访问静态成员;
改过来Out.this.x;-------------->>System.out.println(Out.x);
因为Out.this 表示的是外部类的引用;

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

回复 使用道具 举报
System.out.println(Out.x);首先你这句话Out.x;直接类名调用x,这是静态调用啊,而你int x有没有静态static修饰。所以就报:无法从静态上下文中引用非静态 变量 x。
修改如下:
  1. class Out{
  2. static int x = 1;
  3. class In{
  4.   int x = 2;
  5.   public void show(){
  6.    System.out.println(Out.x);
  7.   }
  8. }
  9. }
  10. class Demo {
  11. public static void main(String[] args) {
  12.   Out.In o = new Out().new In();
  13.   o.show();
  14. }
  15. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

回复 使用道具 举报
本帖最后由 陈宇鹏 于 2013-4-18 20:04 编辑
  1. class Out
  2. {
  3.     int x = 1;
  4.     class In
  5.     {
  6.         int x = 2;
  7.         public void show()
  8.         {
  9.         System.out.println(Out.x);//这里不是这样调用的。这里本身默认省略了out.this., 所以这里一般直接x就能够调用外部类了
  10.                                 //但是当外部类,内部类的成员变量以及函数中的局部变量名一样时,调用规则是这样的
  11.                                 //外部类名.this.x 调用的就是外部类的成员变量
  12.                                 //this.x调用的就是内部类成员变量
  13.                                 //x 调用的就是局部的变量。
  14.         }
  15.     }
  16. }
  17. class Demo
  18. {
  19.     public static void main(String[] args)
  20.     {
  21.         Out.In o = new Out().new In();
  22.         o.show();
  23.     }
  24. }

复制代码
看//之后的
还有就是记着,内部类方法想要访问中想要访问的变量如果有多个同名,一定是默认优先访问自己所在位置中(比如局部方法,比如内部类)的变量

评分

参与人数 1技术分 +1 收起 理由
田磊阳 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马