内部类:
内部类的定义原则;将一个类定义在另一个类的里面,里面那个类就成为内部类(内置类,嵌套类)。
内部访问特点:当描述事物时,事物的内部还有事物,该事物用内部类来描述。(因为内部事物在使用外部事物的内容)
1、内部类可以直接访问外部类中的成员,包括私有成员。(因为内部类持有一个外部类的引用,格式为:外部类.this)
2、外部类要访问内部类中的成员必须要建立内部类的对象。
public class Demo49 { public static void main(String[] args){ Outer out=new Outer(); out.method(); } } class Outer{ private int x=3; void method(){ Inner in=new Inner(); in.function(); } class Inner{ //内部类 void function(){ System.out.println("inner:"+x); } } }
运行结果为:
直接访问内部类中的成员。inner:3
1、当内部类定义在外部类的成员位置上,而且非私有,可以在外部其它类中。可以直接建立内部对象类。
格式:
外部类名.内部类名 变量名 = 外部类对象.内部类对象;
也即是:Outer.Inner.in = new Outer().new Inner();
public class Demo49 { public static void main(String[] args){ // Outer out=new Outer(); // out.method(); Outer.Inner inner=new Outer().new Inner();//直接访问内部类中的成员。 inner.function(); } } class Outer{ private int x=3; void method(){ Inner in=new Inner(); in.function(); } class Inner{ //内部类 void function(){ System.out.println("inner:"+x); } } }
运行结果为:
inner:3
2、当内部类在成员位置上,就可以被成员修饰符所修饰。
比如,private:将内部类在外部类中进行封装。
static:内部类就具备static的特性。(当内部类被static修饰后,只能直接访问外部类中的静态成员,出现了访问局限。)
在外部类中,如何直接访问静态内部类的非静态成员呢?
new Outer.Inner().function();
在外部类中,如何直接访问静态内部类的静态成员呢?
Outer.Inner().function();
注意:1、当内部类定义了静态成员,该内部类必须是static的。
2、当外部类中的静态方法访问内部类是,内部类也必须是static的。
如果分别在外部类,内部类以及内部类成员函数中都定义相同变量,比如x,则获取方法为:
输出结果为:public class Demo49 { public static void main(String[] args){ // Outer out=new Outer(); // out.method(); Outer.Inner inner=new Outer().new Inner();//直接访问内部类中的成员。 inner.function(); } } class Outer{ private int x=3; void method(){ Inner in=new Inner(); in.function(); } class Inner{ //内部类 int x=6; void function(){ int x=9; System.out.println("inner:"+Outer.this.x+" "+"inner:"+this.x+" "+"inner:"+x); } } }
inner:3 inner:6 inner:9
内部类被定义在局部时:
1、不可以被成员修饰符修饰
2、可以直接访问外部类中的成员,(因为还持有外部类中的引用。)但是,不可以访问它所在的局部中的变量。只能访问被final修饰的局部变量。
运行结果为:public class Demo50 { public static void main(String[] args){ new Outer1().method(); } } class Outer1{ int x=3;//内部类可以直接访问成员变量。 void method(){ final int y=4;//内部类只能访问被final修饰的局部变量。 class Inner1{//内部类被定义在局部,也即是method()方法下 void function(){ System.out.println(x); System.out.println(y); } } new Inner1().function(); } }
3
4