Cannot implement abstract class from other package

abstract-class, java

Solution

Your two `foo` methods have the default "package" access. Your `Implementation2` class couldn't even call the method - so it doesn't make much sense to be able to override it.

It's not clear what level of access you want them to have, but the simplest approach is probably to make them both public. At the moment, you're saying that only callers in `package1` can call `BaseClass.foo()`, but only callers in `package2` can call `Implement2.foo()`. That clearly doesn't make much sense. Who do you want to be able to access the method? If you only want callers within the class or a subclass to be able to call it, then make it `protected` - otherwise make it `public`.

See section 6.6 of the Java Language Specification (and the Java tutorial) for more details of access modifiers. In particular, after going through the various access modifiers:

Otherwise, we say there is default access, which is permitted only when the access occurs from within the package in which the type is declared.

Problem

For some reason I seem not to be able to implement an abstract class outside of the package within which it is defined. An abstract class in package1 cannot be implemented in a class in package2. Why is this not legal 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 (build 1.6.0_31-b04-415-10M3646) - OpenJDK Runtime Environment (build 1.7.0-u4-b13-20120301) Tried both Java versions. Not at the same time, of course :)

Original source