Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implement abstract class from other package

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 :)

like image 425
oligofren Avatar asked Nov 28 '22 09:11

oligofren


1 Answers

That method is package level visibility, so you cant override it at other package.

abstract Long foo();

If a method has no modifier (the default, also known as package-private), it is visible only within its own package

If you really need to override it, make it as protected instead.

protected abstract Long foo();

Info

  • Controlling Access to Members of a Class
  • Java Modifier Summary
like image 181
Pau Kiat Wee Avatar answered Dec 19 '22 22:12

Pau Kiat Wee