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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 小邱 中级黑马   /  2015-4-2 22:00  /  588 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*
        内部类:
        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();
        }
}

2 个回复

倒序浏览
细节决定一切,态度决定命运
回复 使用道具 举报
内部类,学习学习~~
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马