Java – an instance of an abstract class

See English answer > interview: can we instantiate abstract class? 15

public abstract class AbstractClassCreationTest {

    public void hello(){
        System.out.println("I'm the abstract class' instance!");
    }

    public static void main(String[] args) {
        AbstractClassCreationTest acct = new AbstractClassCreationtest(){};
        acct.hello();
    }
}

I think this contradicts the norms we can find:

If you try to create an abstract instance, it is a compile time error. The class uses the class instance to create an expression (§ 15.9)

Solution

You may not notice the difference:

new AbstractClassCreationtest(){};

And

new AbstractClassCreationtest();

The extra {} is the body of a new, nameless class that extends the abstract class You created an instance of anonymous class instead of an abstract class

Now, declare an abstract method in an abstract class and see how the compiler forces you to implement it in {} of an anonymous class

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>