Can an anonymous class implement the non abstract method of the abstract class?

Can an Abstract class non abstract method be overridden by using Anonymous class?. The FindBugs tool is issuing " Uncallable method of anonymous class" issue. Please check the below example for more information

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?
            }
        };
    }
}

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


Yes, it is possible!

Reason?

Anonymous class enable you to declare and instantiate a class at the same time, and in your sample code this is the line: ( DerivedAbstractClass derivedAbstractClass = new DerivedAbstractClass() ).

Anonymous Classes are like local classes except that they do not have a name.

In the snipped below, you are extending DerivedAbstractClass and can provide implementations for its abstract methods, and if you want, you may also override non-abstract method too.

But you may want to call super.nonAbstractMethod(); before overriding if required, as below:

 DerivedAbstractClass derivedAbstractClass = new DerivedAbstractClass() {
                @Override
                public void abstractMethod() {
                //anonymous clas providing implemntation

                }

                @Override
                public void nonAbstractMethod() {
                super.nonAbstractMethod();
                //anonymous clas overriding      
                }
            };
链接地址: http://www.djcxy.com/p/24490.html

上一篇: 修改已由另一个选择器激活的元素

下一篇: 一个匿名类可以实现抽象类的非抽象方法吗?