user2048767
user2048767

Reputation: 135

Java static constructor access in child class

I have two classes

package a;

public class A {

  protected void doSomething() {

  }

  protected static class C {
    protected C(int c) {
    }
  }
}

package b;

public class B extends A {

  @Override
  protected void doSomething() {
    C c = new C(0); //compile error
    C c2 = new C(0){}; //legal
  }
}

I have read chapter 6.6.2.2. Access to a protected Constructor of JLS (https://docs.oracle.com/javase/specs/jls/se11/html/jls-6.html) but i am still confused with the explanation. What is wrong with the call of the super constructor new C(0); even if B is a child of A?

Thank you :-)

Upvotes: 2

Views: 158

Answers (1)

user10871691
user10871691

Reputation:

Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

Now, the constructor of C class is protected therefore is accessible outside the a package only by subclasses of C. But B is not a subclass of C ...

As @Amongalen pointed out, the second statement

C c2 = new C(0){};

is legal because it creates an anonymous class that extends C, therefore the protected constructor is visible here.

Upvotes: 7

Related Questions