内部类和 外部类相互访问

内部类:

①静态内部类中可以有非静态的方法

②当内部类中有静态方法或者静态成员变量时,一定是静态内部类

1、外部类访问内部类:

   内部类被static修饰:可以直接new

    Inner in = new Inner();

   内部类没有被static修饰:得先new出来外部类的实例,再new内部类的

    Inner in = new Outer().new Inner();

2、内部类访问外部类:(外部类.this.变量)

3、外部类和内部类中的方法相互访问:

①外部类的静态方法test和非静态内部类的非静态方法voice的相互访问:

   test访问voice       先new外类再new内类,再调方法

  

public class Outerclass {
    class Inner{
        public void voice(){
            System.out.println("voice()");
        }
    }
    public static void test(){
        new Outerclass().new Inner().voice();
    }
    public static void main(String[] args) {
      //主函数调用test方法
       test();13     }
}

  voice访问test        外类.this.方法(持有的外部类的引用)

public class Outerclass {
    class Inner{
        public void voice(){
            Outerclass.this.test();
        }
    }
    public static void test(){
        System.out.println("test()");
    }
    public static void main(String[] args) {
    //主函数调用voice()
        Inner in = new Outerclass().new Inner();
        in.voice();
    }
}

②外部类的非静态方法test和静态内部类中的非静态方法voice之间的相互调用

  voic访问test   

public class Outerclass {
    static class Inner{
        public void voice(){
            new Outerclass().test();
        }
    }
    public void test(){
        System.out.println("test()");
    }
    public static void main(String[] args) {
    //主函数调用voice()方法
        new Outerclass.Inner().voice();
    }
}

  test访问voice

public class Outerclass {
    static class Inner{
        public void voice(){
            System.out.println("voice()");
        }
    }
    public void test(){
      //1、其他类访问外部类中的静态内部类的非静态方法
       // new Outerclass.Inner().voice();
      //2、此处的Outerclass中的test方法访问静态内部类中的非静态方法
       new Inner().voice();
    }
    public static void main(String[] args) {
      //主函数调用test方法
        new Outerclass().test();
    }
}

转自:https://www.cnblogs.com/rgever/p/8902758.html

猜你喜欢

转载自www.cnblogs.com/51python/p/11483134.html