Consider the following codes :

File : C3.java

package G;
public class C3
{
	protected int a=5;
}

File : R3.java

import G.C3;
class R2 extends C3
{
	void doit()
	{
		a=7;
	}
}
class R1 extends R2
{
	void doit(R2 b)
	{
		a=8;      
		b.a=1;   // (1)
	}
}

It gives an error in (1) stating that "a" has protected access in G.C3
"b" is and object of R2 which extends C.R3. Why can't we use "b" to access R2's protected member "a" ?

Recommended Answers

All 4 Replies

Thanks.

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

That effectively means that if we want to access the protected members of a class outside the package through an object of its subtype (say ob), we can do it only within a class (say A) that is either the same class to which ob belongs or its supertype.
That the enclosing class can be a supertype is perhaps proved by this:

class R2 extends C3
{
    void doit( R1 ob)
    {
       ob.a=0;
    }
}

R1 is the subclass of R2. Everything is the same from the previous code.

That effectively means that if we want to access the protected members of a class outside the package through an object of its subtype (say ob), we can do it only within a class (say A) that is either the same class to which ob belongs or its supertype

Yes.

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.