抽象类和匿名类

3
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 的一个实例?

2个回答

11

它不会创建抽象类Two的实例,而是创建一个扩展Two并实例化它的具体匿名类。

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

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

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

2
不要预读我的思维! - Joachim Sauer
有没有办法使MyTwo匿名? - Usman Ismail
@Usman 是的,这就是原帖提问的内容。 - Konrad Garus

2

因为它实现了缺失的display()函数。它返回一个Two的匿名子类。如果你查看编译后的文件,你会看到一个One$1.class,它继承了Two.class!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接