内部类的访问规则:
1,内部类可以直接访问外部类中的成员,包括私有。
之所有可以访问外部类的成员,是因为内部类持有了一个外部类引用, 格式:外部类.this
2,外部类要访问内部类,必须建立内部类对象。
访问格式:
1,当内部类定义在外部类的成员位置上,而且非私有,可以在外部其他类中。
格式为:外部类。内部类 变量名=new 外部类。new 内部类对象。
例如:Outer.Inner in=new Outer().new Inner();
2,当内部类在成员位置上,就可以被成员修饰符所修饰。
比如,private:将内部类在外部类中进行封装。
static:内部类就具备static 的特性。
当内部类被static 修饰后,就只能访问外部类的static成员。出现局限。
外部其他类中,如何访问static内部类的非静态成员?new Outer.Inner().funtion();
外部其他类中,如何访问static内部类的静态成员? Outer.Inner().funtion();
注意:当内部类定义了静态成员,该内部类是static的。
当外部类的静态方法访问内部类时,内部类也必须时静态的。
内部类若有与外部来相同的成员,就近原则。若访问外部类成员则(Outer.this.x).
class Outer{
private int num=3;
class Inner{ //内部类在成员上,可以被private修饰。
//int num=4;
void funtion(){
//int num=5;
System.out.println("inner..."+num); //外部类.this.num
}
}
public void method(){
Inner in=new Inner();
in.funtion();
}
}
public class InnerDemo1 {
public static void main(String[] args) {
//内部类访问 外部类的私有变量
Outer out=new Outer();
out.method(); //inner...3
//直接访问内部类的成员;
Outer.Inner in=new Outer().new Inner();
in.funtion(); //inner...3
}
}
--------------------------------------------------------------------------------
//定义内部类条件:
//当一个类直接访问类成员时,封装到类的里面不直接暴漏。而对外提供方法提供内部事物。
class Body{
private class Heart{
void funtion(){System.out.println("heart");}
}
public void show(){
new Heart();
}
}
---------------------------------------------------------------------------------
内部类定义在局部时,
1,不可以被成员修饰符修饰。(static)
2,可以直接访问外部类中的成员,因为还持有外部类中的引用。
但是不可以访问所在的局部变量,只能访问被final修饰的局部变量。
class Outer{
int x=3;
public void method()
{
class Inner
{
final int y=4;
void funtion()
{
System.out.println("inner...x="+x+"y="+y);
}
}
new Inner().funtion();
}
public void method(final int a)
{
class Inner
{
final int y=4;
void funtion()
{
System.out.println("inner.。。"+a);
}
}
new Inner().funtion();
}
}
public class InnerDemo1 {
public static void main(String[] args) {
new Outer().method();
Outer out=new Outer();
out.method(6); //栈中调用方法执行完后出栈释放。
out.method(7);
}
}