Can an anonymous class implement a non-abstract method of an abstract class?

Is it possible to override the abstract method of an abstract class using an anonymous class ?. The "Uncallable method anonymous class" issue has been released in the FindBugs tool. Please see the example below.

public class BaseClass { // This class is a Library Class. } public abstract class AbstractBaseClass extends BaseClass { public abstract void abstractMethod(); public void nonAbstractMethod() {} } public abstract class DerivedAbstractClass extends AbstractBaseClass { // Here Some more additional methods has been added } public class DemoAbstract { public static void main(String[] args) { init(); } private static void init() { DerivedAbstractClass derivedAbstractClass = new DerivedAbstractClass() { @Override public void abstractMethod() { } @Override public void nonAbstractMethod() { // Is it possible to override like this? } }; } } 
+7
java findbugs
source share
2 answers

Yes it is possible. You can override any non-final, non-static method

+2
source share

Yes it is possible!

Cause?

An anonymous class allows you to declare and instantiate a class at the same time, and in your code example this is the line: ( DerivedAbstractClass derivedAbstractClass = new DerivedAbstractClass() ).

Anonymous classes are similar to local classes, except that they do not have a name.

In the snippet below, you extend DerivedAbstractClass and you can implement its abstract methods, and if you want, you can also override a non-abstract method.

But you can call super.nonAbstractMethod(); before overriding, if necessary, as shown below:

  DerivedAbstractClass derivedAbstractClass = new DerivedAbstractClass() { @Override public void abstractMethod() { //anonymous clas providing implemntation } @Override public void nonAbstractMethod() { super.nonAbstractMethod(); //anonymous clas overriding } }; 
+1
source share

All Articles