Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Protected access restriction for subclass on superclass object

Tags:

java

I know that this has been asked before in this forum but i will ask again since i don't see any good answer (so far).

Here it goes:

package a;
public class A{
    protected int a;
}

package b;
public class B extends A{
}

package c;
public class C extends B{
    public void accessField(){
        A ancient = new A();
        ancient.a = 2;  //A - That wouldn't work.

        a = 2;   //B - That works.
    }

}

Why clause A) won't work? What's the rational behind this restriction on superclass object ancient access in subclass C?
Thanks.

like image 588
yapkm01 Avatar asked Apr 03 '13 22:04

yapkm01


People also ask

Can subclass access protected fields superclass Java?

The protected modifier allows a subclass to access the superclass members directly. But the access should be made inside the subclass or from the same package.

Is protected accessible to subclass?

Because protected is visible to the class itself (like private ) and its subclasses. It is not public. protected instance methods are visible to the class itself, and to instances of subclasses, but not to static methods in subclasses.

Can child class access protected variables in Java?

The protected members are inherited by the child classes and can access them as its own members. But we can't access these members using the reference of the parent class. We can access protected members only by using child class reference.

Can object access protected members in Java?

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.


1 Answers

Protected members can only be accessed outside of the same package if it's via inheritance - i.e. within the hierarchy.

So when you're creating another instance of A from a different package, that's not an inheritance relationship and it thus fails.

As always, this is covered in the JLS, 6.6.2:

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.

like image 163
Michael Berry Avatar answered Oct 22 '22 04:10

Michael Berry