首页 文章

抽象类和匿名类

提问于
浏览
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 回答

  • 9

    它不会创建abstract 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

    因为它实现了缺少的功能display() . 它返回一个匿名子类Two . 如果查看编译后的文件,可以看到这个 . 你将有一个One $ 1.class,它扩展了Two.class!

相关问题