IPolice police = getPolice(); citizen.report(police); }
private static IPolice getPolice() { return new PoliceReal() { @Override
public void catchThief() {
System.out.println(\抓小偷?笑话,抓了小偷我哪儿收保护费去啊.\);
} }; } }
事情结果三:
市民张三丢失手机,向警察报案抓小偷.
抓小偷?笑话,抓了小偷我哪儿收保护费去啊.
附录二 内部类的用法
public class China {
final String nationAnthem = \义勇军进行曲\; //内部类声明的对象,作为外嵌类的成员 Beijing beijing; China() {
beijing = new Beijing(); }
String getSong(){
return nationAnthem; }
//内部类的声明 class Beijing{
String name=\北京\; void speak(){
System.out.println(\我们是:\ + name + \我们的国歌是:\ + getSong()); } }
public static void main(String[] args) { China china = new China(); china.beijing.speak(); } }
附录三 和类有关的匿名类
class Cubic{
double getCubic(int n){ return 0; } }
abstract class Sqrt{
public abstract double getSqrt(int x); }
class A{
void f(Cubic cubic){
//执行匿名类体中重写的getCubic
double result = cubic.getCubic(3); System.out.println(result); } }
public class anonymousClass {
public static void main(String[] args) { A a = new A();
//使用匿名类创建对象,将该对象传递给方法f的参数cubic a.f(new Cubic(){ @Override
double getCubic(int n) { return n*n*n; } });
//使用匿名类创建对象,ss是该对象的上转型对象
//匿名类是abstract类Sqrt的一个子类,所以必须要实现getSqrt方法 Sqrt ss = new Sqrt() { @Override
public double getSqrt(int x) { return Math.sqrt(x); } };
//上转型对象调用子类重写的方法 double m = ss.getSqrt(5); System.out.println(m); } }
附录四 和接口有关的匿名类
interface Cubic{
double getCubic(int n); }
interface Sqrt{
public double getSqrt(int x); }
class A{
void f(Cubic cubic){
//执行匿名类体中实现的getCubic
double result = cubic.getCubic(3); System.out.println(result); } }
public class anonymousClass {
public static void main(String[] args) { A a = new A();
//使用匿名类创建对象,将该对象传递给方法f的参数cubic a.f(new Cubic(){
public double getCubic(int n) { return n*n*n; } });
//使用匿名类创建对象,接口ss存放该对象的引用
//匿名类是实现Sqrt接口的类,所以必须要实现getSqrt方法 Sqrt ss = new Sqrt() { public double getSqrt(int x) { return Math.sqrt(x); } };
//接口回调类实现的方法
double m = ss.getSqrt(5); System.out.println(m); } }