1

Why can a protected interface from a superclass in another package not be implemented in Java/Android? When the parent and the child are in the same package the code below will work. A short explanation is given below:

Parent.java

package package.example;

public class Parent {

    protected interface MyInterface {
        void method();
    }

    protected void protectedMethod() {

    }
}

Child.java

package package.example.child;

import package.example.Parent;

public class Child extends Parent implements Parent.MyInterface { //not possible

    @Override
    public void method() {

    }

    @Override
    public void protectedMethod() {
        //This works
    }
}

The above code will give the warning: 'package.example.Parent.MyInterface' has protected access in 'package.example.Parent'. Can someone explain to me why this is not possible?

Ramonn
  • 281
  • 2
  • 10
  • because it is protected. it's nested in parent, it's not a member of parent – Stultuske Feb 01 '19 at 13:38
  • 1
    Possible duplicate of [What is the difference between public, protected, package-private and private in Java?](https://stackoverflow.com/questions/215497/what-is-the-difference-between-public-protected-package-private-and-private-in) – pedrohreis Feb 01 '19 at 13:39
  • 1
    @PedroH yes and no. he assumes that since Child extends Parent, Child has access to the protected interface declared in Parent – Stultuske Feb 01 '19 at 13:41
  • I have edited the question. The code works when both Parent and Child are in the same package. Also when I have a protected method in my Parent that is overridden by Child the code will build. – Ramonn Feb 01 '19 at 13:46
  • http://javaevangelist.blogspot.com/2012/04/public-protected-and-private-interfaces.html give just an example, but no explanation at all. – Christopher Feb 01 '19 at 14:52

0 Answers0