interface Hierarchy {

}

class Sub1 implements Hierarchy {

}

public class Ob {
    public static void main(String[] args) {
        Hierarchy hie = new Hierarchy(){};//not getting error line 11
        Hierarchy hie1 = new Hierarchy();//while creating like this error line 12
    }
}

hie object created perfectly but hie1 is not creating throwing error that

Hierarchy is abstract cannot be instantiated

please tell me what happens if i put the {} in line 11 what happens actually, why it is not throwing error, when i put {}.

有帮助吗?

解决方案

Adding a block after the new operator (e.g., Hierarchy hie = new Hierarchy(){};) creates an anonymous class that implements the interface, and returns an instance of it. Since your Hierarchy interface is empty, you don't need to implement anything. But if it defined any methods, you'd have to implement them in that block.

其他提示

  Hierarchy hie = new Hierarchy(){}; // this is new implementation for Hierarchy

You have to override all method in Hierarchy interface here.

  Hierarchy hie1 = new Hierarchy();// this will call the constructor of the class

Since Hierarchy is not a class there is no constructor. you can't initialize

The first line instantiates an anonymous class which implements the interface, as signalled by the body enclosed in {}. This is legal. As the interface declares no methods, the body of the class can be empty.

The second line attempts to directly instantiate an interface. This is not legal.

When adding {} at the end of the new, what you are doing is creating an Anonimous Class.
As such, in the first case you are instantiating an object of the class you just made (legal), while in the second case you are trying to instantiate an object with no class (not legal)

In both cases you seem to be attempting to create an anonymous class that implements the interface. But you need {} for doing that. Otherwise, it is not legal. Please note that you cannot instantiate an interface

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top