java中的内部类概念

内部类和外部类可以互相访问私有属性

1.普通内部类实例化方式

外部类.内部类 对象 = new 外部类().new 内部类();
class Outer{//外部类
    private String msg =  "hello word";
    class Inner{//定义一个内部类
        public void print(){
            // Outer.this表示外部类的当前对象
            System.out.println(Outer.this.msg);
        }
    }
}
public class Test{
    public static void main(String args[]){
        Outer.Inner inner = new Outer().new Inner();
        inner.print();
    }
}

2.如果用static定义的内部类,相当于外部类

  static 定义内部类实例化方式

外部类.内部类 对象 = new 外部类.内部类();
class Outer{//外部类
    private static String msg =  "hello word";
    static class Inner{//定义一个static内部类,只可以操作外部内中的static属性或者方法
        public void print(){
            System.out.println(msg);
        }
    }
}
public class Test{
    public static void main(String args[]){
        Outer.Inner inner = new Outer.Inner();
        inner.print();
    }
}

3.方法中定义内部类

  方法中的内部类如果想要访问方法参数和变量则需要加上final关键字

class Outer{//外部类
    private static String msg =  "hello word";
    public void fun(final int num){
       final double score = 59.9;
        class Inner{//方法定义内部类3
            public void print(){
                System.out.println(Outer.this.msg);
                //访问方法参数,和变量
                System.out.println(num);
                System.out.println(score);
            }
        } 
        new Inner().print();
    }
}
public class Test{
    public static void main(String args[]){
        Outer out = new Outer();
        out.fun(100);
    }
}
原文地址:https://www.cnblogs.com/hu1056043921/p/7305571.html