内部类的创建

注意在内部类调用外部类的属性方法时候,使用固定格式Outer.this.属性或方法();

 

public class Outer {
private int age=10;
public void show(){
System.out.println("Outer.show");
System.out.println("Outer.age="+age);
}


//内部类
public class Inner{
public void show(){
int age = 20;
System.out.println("Inner.show");
System.out.println("Inner.age="+age);

//需要调用外部类时候,使用外部类.this.的格式,来调用
//也可以直接更改外部类的私有属性
System.out.println("Outer.age="+Outer.this.age); //输出外部类的age
Outer.this.show(); //调用外部类的show
Outer.this.age = 30; //修改外部类的age
System.out.println("Change Outer.age to 30");
System.out.println("Outer.age="+Outer.this.age); //输出外部类的age
}
}

}

内外部类的调用,注意内部类的实例化必须按照这个格式
public class TestInner {
public static void main(String[] args) {
Outer o = new Outer(); //外部类的创建很简单


//内部类对象的创建需要使用如下格式
Outer.Inner i = new Outer().new Inner();

o.show(); //外部类的show
i.show(); //内部类的show
}
}

 

posted on 2022-06-01 10:26  我爱萨菲娜  阅读(20)  评论(0编辑  收藏  举报