Reputation: 556
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 {}
.
Upvotes: 1
Views: 1738
Reputation: 5279
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
Upvotes: -2
Reputation: 35577
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
Upvotes: 3
Reputation: 311823
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.
Upvotes: 4
Reputation: 3884
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)
Upvotes: 0
Reputation: 310980
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.
Upvotes: 1