java-匿名内部类实践
源码
package com.InnerClass;
public class InnerClassExercise {
public static void main(String[] args) {
//匿名内部类可以当作实参直接传递 简洁高效
f1(new IL() {
@Override
public void show() {
System.out.println(“这时一副名画。。。”);
}
});
//传统方法
f1(new Picture());
}
//静态方法 形参是接口类型
public static void f1(IL il) {
il.show();
}
}
//接口
interface IL {
void show();
}
//类 -> 实现IL 在变成领域 叫做(硬编码)只用一次的话 不灵活
class Picture implements IL{
@Override
public void show() {
System.out.println("这时一副名画。。");
}
}
源码
package com.InnerClass;
public class InnerClassExercise02 {
public static void main(String[] args) {
CellPhone cellPhone = new CellPhone();
//解读
//1. 传递的是实现了 Bell接口的匿名内部类
//2. 重写了ring
//3. Bell bell =new Bell() {
// @Override
// public void ring() {
// System.out.println(“懒猪起床了”);
// }
// }
cellPhone.alarmClock(new Bell() {
@Override
public void ring() {
System.out.println(“懒猪起床了”);
}
});
cellPhone.alarmClock(new Bell() {
@Override
public void ring() {
System.out.println(“小伙伴们上课了”);
}
});
}
}
interface Bell { //铃声接口
void ring();//ring方法
}
class CellPhone {//手机类
public void alarmClock(Bell bell) {//闹钟功能 形参是Bell接口类型
bell.ring();
}
}