Quote:
A protected variable can only be read but not changed
Both of you have your conceptions of protected mixed up. Java in fact defines 4 and not 3 access specifiers, public, protected, private and default or package private. Public members are open to all objects, private members to only the object itself (or "this" in java) and protected members to this and objects of derived classes. The default access specifier is package private, which means that it's open to access by classes in the same package.Quote:
Public is open to anyone, protected is open to members of the same package, and private is only accessible from the same class.
Sorry in advance for the length of the code.
In another package if we were to try to change l, the compiler would generate an error as it is package private.Code:package p;
class c
{
public int i;
protected int j;
private int k;
int l; //this is package private
c()
{
//if no object name is given before the variable, this. is assumed
i=2; //works
j=2; //works
k=2; //works
l=2; //works
}
}
class d extends c //d inherits i,j and l from class c
{
d()
{
i=2; //works
j=2; //works
k=2;//violates encapsulation and therefore generates a compile time error
l=2; //works
}
}
class e
{
c c1; //object of class c
d d1; //object of class d
e()
{
c1=new c();
d1=new d();
e()
{
c1.i=0; //works
c1.j=1; //violates encapsulation and therefore generates a compile time error
c1.k=0; //violates encapsulation and therefore generates a compile time error
c1.l=4; //works
d1.i=0; //works
d1.j=0; //violates encapsulation and therefore generates a compile time error
d1.k=0;//member k was private in class c and therefore not inherited by d, generates a compile time error
d1.l=2;//works
}
}
This fourth access specifier (package private) is an addition to java from C++.
Cheers,
cgkanchi
