java 内部类

心不动则不痛 提交于 2020-03-18 18:02:05

内部类的访问规则:

  1.内部类可以直接访问外部类中的成员,包括私有。

    之所以可以直接访问外部类中的成员,是因为内部类中持有了一个外部类的引用,格式:外部类.this

  2.外部类要访问内部类,必须建立内部类对象。

  3.内部类在成员位置上,就可以被成员修饰符所修饰,比如private:将内部类在外部类中进行封装,static:内部类具有static的特性。

public class InnerClassDemo {
    public static void main(String[] args) {
        //访问方法一:
        Outer outer = new Outer();
        outer.method();
        //访问方法二:
        Outer.Inner in = new Outer().new Inner();
        in.function();
    }
}

class Outer{
    private int x = 4;
    class Inner{
        private int x = 5;
        void function(){
            int x = 6;
            System.out.println("inner:"+x);//6
            System.out.println("inner:"+this.x);//5
            System.out.println("inner:"+Outer.this.x);//4
        }
    }
    void method(){
        Inner in = new Inner();
        in.function();
    }
}

  4.当内部类被静态修饰后,只能直接访问外部类中被static修饰的成员,出现了访问局限。

   5.

public class InnerClassDemo {
    public static void main(String[] args) {
        new Outer.Inner().function();
    }
}

class Outer{
    private static int x = 4;
    static class Inner{
        void function(){
            System.out.println("inner:"+x);
        }
    }
    void method(){
        Inner in = new Inner();
        in.function();
    }
}
public class InnerClassDemo {
    public static void main(String[] args) {
        Outer.Inner.function();
    }
}

class Outer{
    private static int x = 6;
    static class Inner{
        static void function(){
            System.out.println("inner:"+x);
        }
    }
    void method(){
        Inner in = new Inner();
        in.function();
    }
}

  6.当内部类中定义了静态成员,该内部类一定是静态的。

  当外部类中的静态方法访问内部类时,内部类也必须是静态的。

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!