Sarabjeet
Sarabjeet

Reputation: 274

Can anyone please explain me whats happening here : "protected" modifier in java

One thing I have learnt is private in java doesn't really mean same thing as that in C++. private in java is class-based, not object-based. i.e I can access another objects private member directly using "object dot notation" provided that I do so within the class of that object.

However, protected is not so clear. We will have to consider two packages here : pack1 and pack2
We declare classes Alpha and Beta in pack1 package
and declare AlphaSub which extends Alpha from pack1 , and Gamma which also extends from Alpha in pack2 package. !

enter image description here

Here is the class code, I have only included classes relevant to the issue here : Alpha, AlphaSub and Gamma

package pack1;

public class Alpha{
  private int alphaPrivate;
  public int alphaPublic;
  protected int alphaProtected;
  int alphaPP;

  protected int alphaProtected(){
    return 1;
  }
  private int alphaPrivate(){
    return 1;
  }
}

package pack2;

import pack1.Alpha;
public class AlphaSub extends Alpha{
    int alphasubPP;
    private int alphasubPrivate;
    protected int alphasubProtected;
    public int alphasubPublic;

    public void meth() throws CloneNotSupportedException{
        new AlphaSub().alphaProtected(); //OK
        new Gamma().alphaProtected(); /*COMPILE ERROR. */

    }
}

So apparently even though both AlphaSub and Gamma inherits alphaProtected() from Alpha , one cannot invoke Gamma's inherited alphaProtected() from AlphaSub .. If this is the case that protected method of a class can only be called from within that class, wouldn't invocation of clone [inherited by every class from Object class] from another class be impossible ??

Someone can please clarify ?

Upvotes: 2

Views: 82

Answers (1)

Eran
Eran

Reputation: 394146

What you experienced is covered in 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.

In addition, if Id denotes an instance field or instance method, then:

  • If the access is by a qualified name Q.Id or a method reference expression Q :: Id (§15.13), where Q is an ExpressionName, then the access is permitted if and only if the type of the expression Q is S or a subclass of S.

  • If the access is by a field access expression E.Id, or a method invocation expression E.Id(...), or a method reference expression E :: Id, where E is a Primary expression (§15.8), then the access is permitted if and only if the type of E is S or a subclass of S.

  • If the access is by a method reference expression T :: Id, where T is a ReferenceType, then the access is permitted if and only if the type T is S or a subclass of S.

And you are correct, if you replace new Gamma().alphaProtected(); with new Gamma().clone();, you'll get the same compilation error.

Upvotes: 1

Related Questions