AbstractClass abstractClass = new AbstractClass() {
@Override
public void abstractMethod() {
}
};
This block of code means that you are creating an anonymous class which extends AbstractClass
. You can also use the same notation for an interface also.
SomeInterface someImplementingClass = new SomeInterface(){/*some code here*/};
This means you are creating a class that implements SomeInterface
.
Note that there are certain limitation when you are creating an anonymous class. As and anonymous class is already extending the parent type, you cannot make it extend another class as in java you can extend only on class.
This code will help understand concept of overriding methods in anonymous classes
class Anonymous {
public void someMethod(){
System.out.println("This is from Anonymous");
}
}
class TestAnonymous{
// this is the reference of superclass
Anonymous a = new Anonymous(){ // anonymous class definition starts here
public void someMethod(){
System.out.println("This is in the subclass of Anonymous");
}
public void anotherMethod(){
System.out.println("This is in the another method from subclass that is not in suprerclass");
}
}; // and class ends here
public static void main(String [] args){
TestAnonymous ta = new TestAnonymous();
ta.a.someMethod();
// ta.a.anotherMethod(); commented because this does not compile
// for the obvious reason that we are using the superclass reference and it
// cannot access the method in the subclass that is not in superclass
}
}
This outputs
This is in the subclass of Anonymous
Remember that anotherMethod
is implemented in implemented in the subclass that is created as anonymous class. and a
is the reference variable of type Anonymous
i.e. superclass of the anonymous class. So the statement ta.a.anotherMethod();
gives compiler error as anotherMethod()
is not available in Anonymous
.