0

I have 3 classes

package a;

public class A {
    protected void add(){}
}

package b;

import a.A;

public class B extends A {
    public static void main(String[] args) {
        B b=new B();
        b.add();//this is works
    }
}

package b;

public class C {
    public static void main(String[] args) {
        B b=new B(); 
        b.add(); //this will not work 
    }
}

question is B class supposed to have its own copy of the add method, so why can't I access it from C class in the same package?

Mureinik
  • 297,002
  • 52
  • 306
  • 350

3 Answers3

4

Quoting JLS 6.6.2.1:

6.6.2.1. Access to a protected Member

Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.

void add() is a protected member of class A.

Access is permitted within the body of B because it's a subclass of A. Access is not permitted within the body of C because it's not a subclass of A.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
3

B does not have its own copy of the add method. It inherits it from A, where it's protected - I.e., only classes that extend A or reside in the same package can access it.

You could, however, explicitly create a public delegator for it so other class can use it:

public class B extends A {
    @Override
    public void add() {
        super.add();
    }
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

6.6.2. Details on protected Access

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

JLS

Dogukan Zengin
  • 545
  • 3
  • 11