首先说为什么要使用内部类:
1、实现多重继承
2、实现闭包(隐藏关键环节)
3、回调
常见内部类类型
1、非静态内部类
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();
}
}
2、静态内部类
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();
}
}
3、匿名内部类
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();
}
}
实战
1、利用内部类实现多重继承
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());
}
}
2、利用内部类模拟按钮事件(Swing、RCP、Android等)
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);
}
}
相信我们,加入我们
网友评论