《Java基础学习笔记》JAVA基础之内部类

内部类:
1,内部类可以直接访问外部类中的成员,包括私有。
   之所以可以直接访问外部类中的成员,是因为内部类中执有了一个外部类的引用,格式:外部类名.this
2,外部类要访问内部类,必须建立内部类对象。

3,当内部类在成员位置上,就可以被成员修饰符所修饰。
   比如:private:将内部类在外部类封装。
   static:内部类就具备static的特性。
   当内部类被static修饰后,只能直接访问外部类中的static成员,出现了访问局限。

   在外部其它类中,如何直接访问静态内部类中的非静态成员?
   new Outer.Inner().function();

   在外部其它类中,如何直接访问静态内部类中的静态成员?
   Outer.Inner.function();

  

   注意:当内部类中定义了静态成员,该内部类必须是static的。

   当描述事物时,事物的内部还有事物,该事物用内部来描述。
   因为内部事物在使用外部事物中的内容。

   内部类定义在局部时:
   1,不可以被成员修饰符修饰。
   2,可以直接访问外部类中的成员,因为还持有外部类中的引用。
   3,但不是可以访问它所在的局部中的变量,只能访问被final修饰的局部变量。

class Outer
{
 private int x = 3;
 
 class Inner
 {
  int x = 4;
  
  //内部类
  void function()
  {
   int x = 5;
   System.out.println("inner:"+x);
   System.out.println("inner:"+this.x);
   System.out.println("inner:"+Outer.this.x);
   //结果:5,4,3
  }
 }

 void method()
 {
  Inner inner = new Inner();
  inner.function();

  System.out.println(x);
 }
}


class Propram
{
 public static void main(String[] args)
 {
  //直接访问内部类的格式
  Outer.Inner oi = new Outer().new Inner();
  oi.function();
 }
}


 

原文地址:https://www.cnblogs.com/cxmsky/p/2847309.html