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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 戎石锁 中级黑马   /  2012-8-16 16:51  /  1083 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 戎石锁 于 2012-8-20 21:37 编辑

class Person
{
        int x=7;
        class Fun//定义的内部类
        {
                int x=8;
                fun()
                {
                        System.out.println(x);
                }
        }
        show()
        {
                System.out.println(x);
        }
}


向上面这个如果我创建一个内部类使用fun()            
   Persosn.Fun  pp=new Person().new Fun()  
  这样可以直接调用fun().我知道
但现在我想调用外部类的show(),还需要在重新的创建一个外部类对象吗?  

评分

参与人数 1技术分 +1 收起 理由
张立江 + 1 赞一个!

查看全部评分

2 个回复

倒序浏览
内部类中得到当前外围类对象的引用,可以使用.this关键字
  1.   private int num ;  
  2. public Test2(){  
  3.       
  4. }  
  5.   
  6. public Test2(int num){  
  7.     this.num = num;  
  8. }  
  9.   
  10. private class Inner{  
  11.     public Test2 getTest2(){  
  12.         return Test2.this;  
  13.     }  
  14.       
  15.     public Test2 newTest2(){  
  16.         return new Test2();  
  17.     }  
  18. }  
  19.   
  20. public static void main(String [] args){  
  21.     Test2 test = new Test2(5);  
  22.     Test2.Inner inner = test.new Inner();  
  23.     Test2 test2 = inner.getTest2();  
  24.     Test2 test3 = inner.newTest2();  
  25.     System.out.println(test2.num);  
  26.     System.out.println(test3.num);  
  27. }  
  28.    
复制代码
输出结果为5 0
  使用.this后,得到时创建该内部类时使用的外围类对象的引用,new则是创建了一个新的引用。

评分

参与人数 1技术分 +1 收起 理由
张立江 + 1 很给力!

查看全部评分

回复 使用道具 举报
Person.Fun  pp=new Person().new Fun()  ;相当于得到一个内部的变量,要访问外部的成员需要得到外部的实例对象

public class Person
{
         int x=7;
         class Fun//定义的内部类
         {
                 int x=8;
                 void fun()
                 {
                           int x=9;
                         System.out.println(x);
                 }
         }
         void show()
         {
                 System.out.println(x);
         }
}
class Demo{
public static void main (String[] aegs){
  Person.Fun  pp=new Person().new Fun()  ;
  pp.fun();
}
}
运行的结果是
9;
要访问内部变量用this.x;打印的是:8
要是用Person.this.x;打印的是:7;
要想调用show方法必须要得到外部类的实例对象。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马