黑马程序员技术交流社区

标题: 关于内部类(谢谢,已解决) [打印本页]

作者: 戎石锁    时间: 2012-8-16 16:51
标题: 关于内部类(谢谢,已解决)
本帖最后由 戎石锁 于 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(),还需要在重新的创建一个外部类对象吗?  

作者: 周瑞    时间: 2012-8-16 17:14
内部类中得到当前外围类对象的引用,可以使用.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则是创建了一个新的引用。
作者: 胡刚涛    时间: 2012-8-16 17:55
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方法必须要得到外部类的实例对象。





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2