Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I override a method of an Abstract Inner Class?

My codes are:

core/Base.java

package core;
public class Base {
    public abstract class AbstractInner {
        abstract void run();
    }
}

Test.java

class Test extends core.Base {
    class Inner extends AbstractInner {
        void run() {}
    }
}

javac complains like the following;

shell> javac -cp . Test.java 
Test.java:2: Test.Inner is not abstract and does not override abstract method run() in core.Base.AbstractInner
    class Inner extends AbstractInner {
    ^

What is my mistake?

If Base is in the same package as Test, compile is successful. I don't know why.

like image 730
user1086901 Avatar asked Sep 02 '25 08:09

user1086901


1 Answers

There are some non-intuitive rules governing overridibility of package-private members. Essentially, you can override a package-private method if the overriding class is in the same package. If it's not, it does not have visibility to see AbstractInner's declaration of run() and so can't override it. Instead you are declaring a new method with the same signature.

If you make run() protected (or public) in AbstractInner (and thus in Inner as well) instead of using the default visibility, it will work as intended.

Recall that only in interfaces are declared methods implicitly public. In abstract classes, they are implicitly package-private.

like image 171
Mark Peters Avatar answered Sep 05 '25 01:09

Mark Peters