黑马程序员技术交流社区

标题: 关于内部类 [打印本页]

作者: 小邱    时间: 2015-4-2 22:00
标题: 关于内部类
/*
        内部类:
        1.内部类可以直接访问外部类的成员
        2.外部类要访问内部类必须创建内部类的对象
       
        外部类直接访问非私有内部类:外部类名.内部类名 对象名=外部类对象.内部类对象;
        如:Outer.Inner2 oi=new Outer().new Inner2();
       
       
*/

class Outer
{
        private int x=3;
        int y=2;
       
        private void method()
        {
                System.out.println("Outer_method");
        }       
        void show()
        {
                Inner in=new Inner();//外部类要访问内部类:需创建内部类的对象
                in.function();
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private class Inner//当内部类在外部类成员的位置时,可以用成员修饰符修饰,如private,static
                                                //将内部类进行私有化禁止创建内部类对象,可以通过成员方法调用内部类方法
        {
                int x=6;
                void function()
                {
                        int x=9;
                        method();//内部类可以直接访问外部类的成员,无论是私有的还是非私有的
                       
                        //this.x表示访问当前类的x
                        //Outer.this.x 表示访问指定外部类的成员,格式:指定外部类名.this.成员名
                        System.out.println("Inner"+x+this.x+Outer.this.x);
                        System.out.println(y);//y的原型是:Outer.this.y    省略了Outer.this
                }
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////
        class Inner2
        {
                int x=6;
                void function()
                {
                        int x=9;       
                        System.out.println("Inner2"+x+this.x+Outer.this.x);
                }
        }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class Test
{
        public static void main(String[] args)
        {
                //直接访问内部类的成员,格式:外部类名.内部类名 对象名=外部类对象.内部类对象;
                Outer.Inner2 oi=new Outer().new Inner2();
                oi.function();
               
                Outer out=new Outer();
                out.show();
        }
}
作者: jiandonn    时间: 2015-4-2 22:12
细节决定一切,态度决定命运
作者: 俊勇    时间: 2015-4-2 22:32
内部类,学习学习~~




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