黑马程序员技术交流社区

标题: Java练习(6):内部类演练 [打印本页]

作者: hoshan1    时间: 2015-11-13 20:58
标题: Java练习(6):内部类演练

1,内部类可以直接访问外部类中的成员,包括私有。
        之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式 外部类名.this
2,外部类要访问内部类,必须建立内部类对象。
class Outer
{
        private int x = 3;
        class Inner//内部类
        {
                int x = 4;
                void function()
                {
                        //调用外部内中的方法
                        haha();
                        int x = 5;
                        System.out.println("Outer:"+Outer.this.x+"  innner :"+this.x+"  function:"+x);
                }
        }
        void haha()
        {
                System.out.println("哈哈哈哈哈哈");
        }
        void method()
        {
                //定义内部类对象
                Inner in = new Inner();
                //调用内部类方法
                in.function();
        }
}
class  Demo
{
        public static void main(String[] args)
        {
              //定义外部类
                Outer out = new Outer();
             //引用外部类方法
                out.method();

                //直接访问内部类中的成员。
                Outer.Inner in = new Outer().new Inner();
            //调用内部类方法
                in.function();
        }
}






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