Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why an instance of inherited class can't access to protected member of base class in different package

Tags:

java

I have 3 class A, B, C :

package com.training.protectedclass.A;

public class A
{
    protected int   value;
}

package com.training.protectedclass.B;
import com.training.protectedclass.A.A;

public class B extends A
{
    public void test()
    {
        this.value = 10;
        A a = new A();
        a.value = 12; //Error => The field A.value is not visible
    }
}

package com.training.protectedclass.C;

import com.training.protectedclass.B.B;
import com.training.protectedclass.A.A;

public class C extends A
{
    public void test()
    {           
        B b = new B();
        b.value = 45; //Error => The field A.value is not visible
    }
}

When the inherited class exists in different package than the base class, it can't access the protected member of base class. But when all the three class exist in the same package the above errors disappear and the code is compiled without errors.

Can anyone explain me the cause of each error launched in my code above?

Thanks :)

like image 615
Naruto Biju Mode Avatar asked Oct 23 '25 17:10

Naruto Biju Mode


2 Answers

This is because protected in Java means two things: 1) inherited classes can see protected members that they inherit, and 2) other classes in the same package can see protected members (even if they don't inherit the member).

So in class B you have inherited value and thus you can access it via this.value, but as class A is in another package you can't see a.value. This is because when you call a.value you are accessing a member of a class in another package rather than the inherited version of the field value.

In the case of class C, you can't access any protected member of B because you neither inherit from B nor are in the same package as B.

like image 121
neuronaut Avatar answered Oct 25 '25 07:10

neuronaut


The Java Language Specification defines the protected access modifier this way:

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.

When you have this.value = 10;, the B object accesses to one of its own members, which is a protected field declared in the superclass. On the other hand, when you have new A().value, the B object tries to access a protected member of an object that it doesn't implement.

like image 42
JB Nizet Avatar answered Oct 25 '25 06:10

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!