A .内部类的访问规则:
1,内部类可以指直接访问外部类中的成员,包括私有成员。
之所以可以直接访问外部类中的成员,是因为内部类中直接持有外部类的引用,格式 外部类名.this
2, 外部类若要访问内部类,需要创建内部类对象。
class Outer{
private int num=5;
class Inner{
//int num=6;
void function(){
//int num=7;
System.out.println("inner "+num);
}
}
void method(){
Inner in=new Inner();
in.function();
}
}
public class InnerClassDemo {
public static void main(String[] args){
Outer ou=new Outer();
ou.method();
}
}
inner 5
如果取消注释,那么num=7,如果在输出语句中的num前面加上this. ,则num输出6。如果在这种情况下还想要输出外部类中的num=5,
应该在输出语句中的num前面加上Outer.this. 。
B .访问格式:(不做重点掌握,知道就行)
1,当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中直接建立内部类对象
格式:
外部类名.内部类名 变量名=外部类对象.内部类对象;
例如,要在InnerClassDemo类中直接使用内部类中的function方法,则代码如下
Outer.Inner in=new Outer().new Inner();
in.function();
2,当内部类在成员位置上,就可以被成员修饰符所修饰。
比如,private:将内部类在外部类中进行封装。
static:内部类就具备了static的特性
当内部类被static修饰后,只能直接访问外部类中的static成员,出现了访问局限
在外部其他类中,如何直接访问静态内部类的非静态成员:
new Outer.Inner().function();
class Outer{
private static int num=5;
static class Inner{
void function(){
System.out.println("inner "+num);
}
}
在外部其他类中,如何直接访问静态内部类的静态成员:
Outer.Inner.function();
class Outer{
private static int num=5;
static class Inner{
static void function(){
System.out.println("inner "+num);
}
}
注意:当内部类中定义了静态成员时,内部类必须是静态的
当外部类中的静态方法访问内部类时,内部类也必须是static
C.内部类定义在局部时
1,不可以被成员修饰符修饰。
2,可以直接访问外部类中的成员,因为还持有外部类的引用。
但是不可以访问它所在的局部中的变量,只能访问被final修饰的局部变量。