Java – abstract classes cannot be implemented from other packages

For some reason, I can't seem to implement an abstract class outside the package that defines it Abstract classes in Package1 cannot be implemented in classes in package2 Why isn't this legitimate Java?

package com.stackoverflow.abstraction.package1;

abstract public class BaseClass {
    abstract Long foo();
}

package com.stackoverflow.abstraction.package1;

public class Implement1 extends BaseClass {
    @Override
    Long foo() {
        return null;
    }
}


package com.stackoverflow.abstraction.package2;

import com.stackoverflow.abstraction.package1.BaseClass;

/** Compiling this class will output
* - Implement2 is not abstract and does not override abstract method foo() in BaseClass
* - error: method does not override or implement a method from a supertype
*/

public class Implement2 extends BaseClass {
    @Override
    Long foo() {
        return null;
    }
}

Running: OS X 10.6 8 – Java (TM) se runtime environment (version 1.6.0_31-b04-415-10m3646) – openjdk runtime environment (version 1.7.0-u4-b13-20120301) tried two Java versions Of course not at the same time:)

Solution

Your two foo methods have default package access Your implementation2 class can't even call this method - so it doesn't make much sense to override it

It's not clear what level of access you want them to have, but the easiest way may be to make them public For now, you just say that callers in Package1 can call baseClass Foo (), but only callers in package2 can call implement2 foo(). This obviously doesn't make much sense Who do you want to be able to access this method? If you only want callers in a class or subclass to be able to call it, protect it - otherwise expose it

For more details on access modifiers, see section 6.6 of the Java language specification (and Java Tutorial) In particular, after browsing the various access modifiers:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>