A standalone Abstract class's Object can't be made but an anonymous abstract class object can be made because it is providing implementation then and there.
The reason why Java doesn't allow object of abstract class is , because it doesn't have any implementation for any method or for some of the methods , so how could you have an object of incomplete class. But in Anonymous way here you are giving it implementation so it is allowing you to have an object.
Same case with interface
AbstractDemo ad = new AbstractDemo() {
@Override
void showMessage() {
// TODO Auto-generated method stub
}
@Override
int add(int x, int y) {
// TODO Auto-generated method stub
return 0;
}
};
Here AbstractDemo class is abstract , but its implementation class can have the object so , here anonymous class code is implementing the code , hence that is perfectly allowed to have object.
More digging into it , see the code below , MyAbstractClass is an abstract class , now if you comment out
abstract void play();
then it works fine , Java is allowing to make object of this abstract class but when you uncomment that like ,it denies because it doesn't have any implementation about that method , so denies to make object.
abstract class MyAbstractClass {
private String name;
public MyAbstractClass(String name)
{
this.name = name;
}
public String getName(){
return this.name;
}
abstract void play();
}
public class Test2 {
public static void main(String [] args)
{
MyAbstractClass ABC = new MyAbstractClass("name") {
};
System.out.println(ABC.getName());
}
}
check carefully it is {} after the constructor calling , that means no more implementation required , or you can override its one of method or more.