//外部类
public class Demo {
private int id;
private String name;
//成员内部类
class Inner {
private String name;
//内部类中不能包括静态成员,但是可以包括静态常量
private static final String constant = "静态常量";
//内部类方法
public void method() {
//访问外部类属性
id = 1;
System.out.println(id);
//访问外部类重名属性,优先访问内部类
Demo.this.name = "外部类张三";
System.out.println(Demo.this.name);
//访问内部类属性
name = "内部类张三";
System.out.println(name);
}
}
}
//调用内部类方法
Demo.Inner inner = new Demo().new Inner();
inner.method();
静态内部类
//外部类
public class Demo {
private int id;
private String name;
//静态内部类,和外部类同外部类同级
static class Inner {
private String state;
//静态内部类,可以有静态成员
private static int num;
public void method(){
//调用外部类属性(new外部类对象)
Demo demo = new Demo();
demo.id = 1;
System.out.println(demo.id);
//内部类属性和方法(直接调用)
state = "内部类状态";
System.out.println(state);
}
}
}
//调用静态内部类方法
Demo.Inner inner = new Demo.Inner();
inner.method();
局部内部类
//外部类
public class Demo {
private int id;
//外部类方法
public void method() {
//定义局部变量
String name = "局部变量张三";
//局部内部类(不能用访问任何修饰符修饰)
class Inner {
//局部内部类属性
private int age;
//局部内部类 ,只能在当前方法中使用
public void innerMethod() {
//直接可以访问外部类属性
id = 1;
System.out.println(id);
//访问内部类属性
age = 18;
System.out.println(age);
//只有局部变量为常量时,局部内部类才能访问(1.7之前必须得家final,1.8之后默认带final),以保证变量的声明周期与自身相同
System.out.println(name);
}
}
//只有在外部类方法内部创建 局部内部类的对象 才能调用局部内部类
Inner inner = new Inner();
inner.innerMethod();
}
}
//调用
Demo demo = new Demo();
demo.method();
匿名内部类(没有名字的局部内部类)
必须继承一个父类或者实现一个接口,class文件生成个xxx.$1.class的文件



