欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Java中的隐藏内部类(Anonymous Classes)

最编程 2024-07-19 12:53:07
...

参考链接: Java类之anonymous

原文链接:  点击打开链接 

1. 匿名类需要继承一个方法或接口 

不使用匿名内部类来实现抽象类 

abstract class Person{

    public abstract void eat();

}

class Child extends Person{

    public void eat(){

        System.out.println("eat something");

    }

}

public class Ordinary {

    public static void main(String[] args) {

        Person p = new Child();

        p.eat();

    }

}

2. 匿名内部类的基本实现

abstract class Person{

    public abstract void eat();

}

public class Ordinary {

    public static void main(String[] args) {

        Person p = new Person(){

            public void eat(){

                System.out.println("eat something");

            }

        };

        p.eat();

    }

}

 3. 在接口上使用匿名内部类

interface Person{

    public abstract void eat();

}

public class Ordinary {

    public static void main(String[] args) {

        Person p = new Person(){

            public void eat(){

                System.out.println("eat something");

            }

        };

        p.eat();

    }

}