内部类:定义在类里的类
成员内部类
局部内部类
静态内部类
匿名内部类
// 成员内部类
public class Demo01{
public static void main(String[] args){
Outer outer = new Outer();
//通过外部类对象创建内部类对象
Outer.Inner inner = outer.new Inner();
inner.setId(20);
System.out.println(inner.getId());
}
}
public class Outer {
//成员属性
public int num = 1;
//成员内部类
public class Inner{
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
}
// 局部内部类:作用域只在方法
public class Demo02{
public static void main(String[] args){
Outer outer = new Outer();
outer.method01();
}
}
public class Outer{
public void method01{
class Inner{
private int id;
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
}
Inner inner = new Inner();
inner.setId(10);
}
}
// 静态内部类
public class Demo03 {
public static void main(String[] args) {
Outer.Inner inner = new Outer.Inner();
inner.setId(10);
System.out.println("内部类属性:"+inner.getId());
}
}
public class Outer {
//静态属性
public static int num;
//静态内部类
public static class Inner{
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
}
// 匿名内部类
// 减少了类的创建,只适用于对象的方法只调用一次或者少次
public class Demo04{
Test test = new Test();
test.method();
System.out.println("---使用多态---");
MyInterface myInterface = new Test();
myInterface.method();
System.out.println("---使用匿名内部类---");
MyInterface2 myInterface2 = new MyInterface(){
@Override
public void method02() {
System.out.println("匿名内部类创建的方法");
}
};
myInterface2.method02();
}
// Test类
public class Test implements MyInterface {
@Override
public void method() {
System.out.println("实现接口重写的方法");
}
}
// 接口类1
public interface MyInterface {
void method();
}
// 接口类2
public interface MyInterface2 {
void method02();
}



