集册 Java实例教程 创建匿名类

创建匿名类

欢马劈雪     最近更新时间:2020-01-02 10:19:05

476
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
创建匿名类

public class HelloWorldAnonymousClasses {
/*来自 
 n o w j a v a . c o m - 时代Java*/


    interface HelloWorld {

        public void greet();


        public void greetSomeone(String someone);

    }


    public void sayHello() {


        class EnglishGreeting implements HelloWorld {

            String name = "world";


            public void greet() {

                greetSomeone("world");

            }


            public void greetSomeone(String someone) {

                name = someone;// 来 自 时 代 J a v a 公 众 号

                System.out.println("Hello " + name);

            }

        }


        HelloWorld englishGreeting = new EnglishGreeting();


        HelloWorld frenchGreeting = new HelloWorld() {

            String name = "tout le monde";


            public void greet() {

                greetSomeone("tout le monde");

            }


            public void greetSomeone(String someone) {

                name = someone;

                System.out.println("Salut " + name);

            }

        };


        HelloWorld spanishGreeting = new HelloWorld() {

            String name = "mundo";


            public void greet() {

                greetSomeone("mundo");

            }


            public void greetSomeone(String someone) {

                name = someone;

                System.out.println("Hola, " + name);

            }

        };

        englishGreeting.greet();

        frenchGreeting.greetSomeone("Fred");

        spanishGreeting.greet();

    }


    public static void main(String... args) {

        HelloWorldAnonymousClasses myApp = new HelloWorldAnonymousClasses();

        myApp.sayHello();

    }

}


展开阅读全文