Originally posted by vini singh:
its showing compiler error as protected variable cant be accessed through the parent reference in subclass.
A subclass can access the superclass's protected members only through a reference of the subclass's type
The reason for this rule is simple. Imagine that parent class P has subclasses C1 and C2. There's no reason to think that the classes C1 and C2 have any special security relationship. But without this rule, an instance of C1 would have access to some otherwise-private variables in instances of C2.
class C1 extends P
{
}
class C2 extends P
{
private int c2variable=12;
}
class C2
{
protected int c2variable=12;
}
public class TestC2
{
C2 c2instance=null;
public int createInstance(C2 c2instance)
{
this.c2instance=c2instance;
this.c2instance.c2variable=20;
return this.c2instance.c2variable;
}
public static void main(String[] args)
{
TestC2 test=new TestC2();
C2 c2=new C2();
System.out.println("Original c2 var value is "+c2.c2variable);
System.out.println("Value :"+test.createInstance(c2));
}
}
C:\sai>java TestC2
Original c2 var value is 12
Value :20
C:\sai>javac TestC2.java
TestC2.java:8: c2variable has private access in C2
this.c2instance.c2variable=20;
^
TestC2.java:9: c2variable has private access in C2
return this.c2instance.c2variable;
^
TestC2.java:16: c2variable has private access in C2
System.out.println("Original c2 var value is "+c2.c2variable);
^
3 errors
public class TestC3 extends C2
{
public static void main(String[] args)
{
TestC3 test=new Testc3();
test.modifyVariable();
}
public void modifyVariable()
{
super.c2variable=20;
System.out.println("In method c2variable modified to
:"+super.c2variable);
}
}
C:\sai>javac TestC3.java
TestC3.java:5: cannot find symbol
symbol : class Testc3
location: class TestC3
TestC3 test=new Testc3();
^
TestC3.java:11: c2variable has private access in C2
super.c2variable=20;
^
TestC3.java:12: c2variable has private access in C2
System.out.println("In method c2variable modified to :"+super.c2variable);
^
3 errors
package n;
class superc
{
protected int x=6;
}
package n;
class subc extends superc
{
public static void main(String s[])
{
superc c=new superc();
System.out.println(c.x);
}
}
C:\sai>javac -d . subc.java
C:\sai>java n/subc
6
When we can access the protected property inside the same package through a superclass reference, then why have they enforced the restrictions on accessing the protected property in other packages.
Regards.
Lookout! Runaway whale! Hide behind this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
|