接口匿名内部类与抽象类的匿名内部类

package yuwei.com;

/*
 * 使用接口创建匿名内部类的使用一般只是使用了一次的类*/
interface Product{
    int getPrice();
    String getName();
}
/*
 * 使用抽象类创建匿名内部类*/
abstract class ProductTwo{
    private String name;
    private int Price;
    public abstract int getPrice();
    public  String getName()
    {
        return this.name;
    }
    public ProductTwo() {}
    public ProductTwo(String name) {
        this.name = name;
    }
}
class AnonymousClass{
    public void test(Product p) {
        System.out.println("Price:"+p.getPrice() + "\tName:" + p.getName());
    }
    public void test1(ProductTwo p) {
        System.out.println("Price:"+p.getPrice() + "\tName:" + p.getName());
    }
}
public class AnonymousClassDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        AnonymousClass A = new AnonymousClass();
        A.test(new Product()
                {
                    public int getPrice() {
                        return 10;
                    }
                    public String getName() {
                        return "AAAAAA";
                    }
                });

        System.out.println("********************");
        //创建无参数构造器的匿名类
        A.test1(new ProductTwo()
                {
                    public int getPrice() {
                        return 23;
                    }
                    //重写父类的getName()
                    public String getName() {
                        return "AD钙";
                    }
                });
        System.out.println("********************");
        //创建无参数构造器的匿名类
        A.test1(new ProductTwo("蒙牛")
        {
            public int getPrice() {
                return 98;
            }       
        });

    }

}

猜你喜欢

转载自blog.csdn.net/weixin_40051278/article/details/80504749