首页 > 代码库 > 面向对象(6)之匿名内部类

面向对象(6)之匿名内部类

1.案例演示

    * 匿名内部类的方法调用

案例:

public class Demo_NoNameInnerClass {

    public static void main(String[] args){

        Outer o = new Outer();        

        o.method();

    }

 

}

 

//匿名内部类只适用于一个方法的重写

interface Inter{

    public void show1();

    public void show2();

}

class Outer{

    public void method(){

        Inter i=new Inter(){

 

            public void show1() {

                // TODO Auto-generated method stub

                System.out.println("show1");

            }

 

            public void show2() {

                // TODO Auto-generated method stub

                System.out.println("show2");

                /*public void show3() {        

                 *         System.out.println("show3");

                 *             } 不适用内部有自己的方法*/

            }

            

        };

        i.show1();

        i.show2();

    }

}

2.匿名内部类在开发中的应用

 

* A:代码如下

public class Test1_NoNameInnerClass {

    public static void main(String[] args){

        PersonDemo pf= new PersonDemo();

        pf.method(new Person(){//匿名内部类

            public void show(){

                System.out.println("show");

            }

        });

         //pf.method(new Student());不用内部类相当于 Person p=new Person();父类引用子类对象

    }

 

}

 

abstract class Person{

    public abstract void show();

}

 

class PersonDemo{

    public void method(Person p){

        p.show();

    }

}

 

 

class Student extends Person{

 

    public void show() {

        // TODO Auto-generated method stub

        System.out.println("show");

    }

    

}

输出:

Show

3.面试题

 

        按照要求,补齐代码

        interface Inter { void show(); }

        class Outer { //补齐代码 }

        class OuterDemo {

            public static void main(String[] args) {

                 Outer.method().show();

             }

        }

        要求在控制台输出"HelloWorld

public class Test_NoNameInnerClass {

    public static void main(String[] args){

        Outer.method().show();

        /*Inter i= Outer.method();

        i.show();*/

    }

 

}

 

interface Inter{

    void show();

}

 

class Outer{

    public static Inter method(){// Outer.method().show(); Outer.method()可知methodstatic 返回类型为Inter型对象与方法返回值同一类型

        return new Inter(){//返回子类对象

            public void show(){

                System.out.println("show");

            }

        };//注意匿名内部类以};结尾

}

}

面向对象(6)之匿名内部类