JAVA 内部类

来源:互联网 发布:国考行测技巧知乎 编辑:程序博客网 时间:2024/06/08 13:38

//仅作为学习笔记


/*将一个类定义在另一个类的内部,里面的那个类就称为内部类(内置类,嵌套类)访问特点:内部类可以直接访问外部类的成员,包括私有成员而外部类要访问内部类中的成员,必须建立内部类的对象访问格式:1,当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中可以直接建立内部类对象格式:外部类名.内部类名 变量名 = 外部类对象.内部类对象如:Outer.Inner in = new Outer().new Inner();2,当内部类在成员位置上,可以被成员修饰符所修饰比如:private ,将内部类在外部类中进行封装  static, 内部类就具备static的特性  当内部类被static修饰后,只能直接访问外部类中的static成员。出现了访问局限  在外部其他类中,如何访问static内部类的非静态成员?  new Outer.Inner().function();在外部其他类中,如何直接访问static内部类的静态成员呢?Outer.Inner.function();注意:内部类中定义了静态成员,该内部类必须是static的当外部类中的静态方法访问内部类时,内部类必须是static*/class Outer{private  int x =3;static class Inner{//static  void function()//error 内部类中不能有静态成员void function(){int x = 6;System.out.println("Inner :"  +  x);// x=6//System.out.println("Inner :"  +  Outer.this.x);//x=3//之所以内部类可以直接访问外部类的成员 ,是因为内部类中持有了一个外部类的引用,外部类名.this.}}static void method(){Inner in = new Inner();in.function();}}class InnerClassDemo {public static void main(String[] args) {Outer ou = new Outer();ou.method();//不可以直接访问内部类的成员 //不过可以这样写//Outer.Inner in = new Outer().new Inner();//in.function();new Outer.Inner().function();}} 


原创粉丝点击