抽象类和匿名类 [英] abstract class and anonymous class

查看:30
本文介绍了抽象类和匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

abstract class Two {
    Two() {
        System.out.println("Two()");
    }
    Two(String s) {
        System.out.println("Two(String");
    }
    abstract int  display();
}
class One {
    public Two two(String s) {
        return new Two() {          
            public int display() {
                System.out.println("display()");
                return 1;
            }
        };
    }
}
class Ajay {
    public static void main(String ...strings ){
        One one=new One();
        Two two=one.two("ajay");
        System.out.println(two.display());
    }
}

我们不能实例化一个抽象类那么为什么函数Two two(String s)能够创建一个抽象类Two的实例???????

we cannot instantiate an abstract class then why is the function Two two(String s) able to create an instance of abstract class Two ????

推荐答案

它不会创建抽象 Two 的实例.它创建了一个具体的匿名类,该类扩展了 Two 并对其进行了实例化.

It does not create an instance of abstract Two. It creates a concrete, anonymous class that extends Two and instantiates it.

这几乎等同于使用这样的命名内部类:

It's almost equivalent to using a named inner class like this:

class One {
    public Two two(String s) {
        return new MyTwo();
    }

    class MyTwo extends Two {
        public int display() {
            System.out.println("display()");
            return 1;
        }
    }
}

这篇关于抽象类和匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆