为什要使用内部类
- 实现多重继承
- 实现闭包(隐藏关键环节)
- 事件回调
内部类的类型
- 非静态内部类
public class NoStaticInsideClass {
private @Setter String name;
private @Setter int age;
class UserAction{
public void call() {
System.out.println(name + " "+age);
}
}
public static void main(String[] args) {
NoStaticInsideClass ni = new NoStaticInsideClass();
ni.setName("张三");
ni.setAge(18);
UserAction ua = ni.new UserAction();
ua.call();
}
}
- 静态内部类
public class StaticInsideClass {
private static String name;
private static int age;
static class UserAction{
public void call() {
System.out.println(StaticInsideClass.name + " "+StaticInsideClass.age);
}
}
public static void main(String[] args) {
StaticInsideClass.name = "张三";
StaticInsideClass.age = 18;
UserAction ua = new StaticInsideClass.UserAction();
ua.call();
}
}
- 匿名内部类
public class AnonymousInsideClass {
private @Setter String name;
private @Setter int age;
UserAction ua = new UserAction(){
public void call() {
System.out.println(name + " "+age);
}
};
public static void main(String[] args) {
AnonymousInsideClass ni = new AnonymousInsideClass();
ni.setName("张三");
ni.setAge(18);
ni.ua.call();
}
}
实战
- 利用内部类实现多重继承
class Father {
public String name() {
return "张";
}
}
class Mather {
public String face() {
return "白色";
}
}
public class Child extends Father {
class Child2 extends Mather{
public String childPeculiarity(){
return "继承了爸爸的姓("+name() + ")和妈妈的皮肤("+face()+")";
}
}
public static void main(String[] args) {
System.out.println("儿子的特点是:" + new Child().new Child2().childPeculiarity());
}
}
- 利用内部类实现按钮事件回调
public interface BtnClickListener {
public void call();
}
public class Button {
public void addClickListener(BtnClickListener event) {
event.call();
}
}
public class UserClick {
/**
* 匿名内部类
*/
BtnClickListener bl = new BtnClickListener() {
@Override
public void call() {
System.out.println("当用户点击了按钮后,执行了此方法");
}
};
public static void main(String[] args) {
new UserClick().triggerClick();
}
/**
* 模拟触发按钮事件
*/
public void triggerClick() {
new Button().addClickListener(bl);
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/87112943bc6e6e4429f80a16fa60ffd7.webp?x-image-process=image/format,png)
转载自:https://www.jianshu.com/p/7d19315cd321