定义:在一个类内部声明一个类,叫做这个类的内部类
public class Neibu01 {
private String st1="abc";
private int in1=12;
class Neibu02{//内部类
int in2=21;//优先访问内部类成员
int in1=14;//优先访问内部类成员
public void shwo() {
System.out.println(st1);
System.out.println(in2);
}
}
}
测试类
public class Text01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建 外部类对象,第一种写法
Neibu01 neibu01=new Neibu01();
Neibu02 neibu02=neibu01.new Neibu02();
//第二种写法
Neibu02 neibu_02=new Neibu01().new Neibu02();
neibu02.shwo();
}
// TODO Auto-generated method stub
//创建 外部类对象,第一种写法
Neibu01 neibu01=new Neibu01();
Neibu02 neibu02=neibu01.new Neibu02();
//第二种写法
Neibu02 neibu_02=new Neibu01().new Neibu02();
neibu02.shwo();
}
}
局部内部类定义:在一个类中方法里声明一个类
public class Outer {
private String name="absc";
private int age=18;
public void show() {
String address="南京";
class Inner{
private String phone="15542665398";
public void show2() {
System.out.println(name);
System.out.println(Outer.this.age);
System.out.println(address);
System.out.println(this.phone);
}
}
Inner inner=new Inner();
inner.show2();
}
}
private String name="absc";
private int age=18;
public void show() {
String address="南京";
class Inner{
private String phone="15542665398";
public void show2() {
System.out.println(name);
System.out.println(Outer.this.age);
System.out.println(address);
System.out.println(this.phone);
}
}
Inner inner=new Inner();
inner.show2();
}
}
测试类:
public class TextOuter {
public static void main(String[] args) {
// TODO Auto-generated method stub
Outer outer=new Outer();
outer.show();
}
// TODO Auto-generated method stub
Outer outer=new Outer();
outer.show();
}
}
匿名内部类:必须继承一个类或者实现一个接口