| Author |
Protected Memebres Cannot Acces In Sub class...
|
Thangaraj Selvamani
Ranch Hand
Joined: Sep 20, 2008
Posts: 61
|
|
why it shows compile error eventhough "i" variable declared has a protected member... according to my knowledge protected members can be inherited from the super class to base class eventhough both class in different pckages.
|
 |
Paul Somnath
Ranch Hand
Joined: May 19, 2008
Posts: 177
|
|
|
Read this thread.
|
Preparing for SCJP 6.0
|
 |
subhasish nag
Ranch Hand
Joined: Apr 25, 2008
Posts: 101
|
|
I'st ,you need to import p1.A to directly access the class. And the reason actualy needed by you is "protected members can only be accessible by sub classes from diffrent package only through inheritance.But they can be accesible in the clild class if you accesss it by creating child class instance and access through it(through inheritance).But it can't be accesible by parent class instance in child class"
|
Thanks,<br />Subhasish
|
 |
Jolly Tiwari
Ranch Hand
Joined: Mar 26, 2006
Posts: 77
|
|
Hi! subhashish, This is true that you can access a protected data member through inheritence across packages but i will like to emphasize on the fact that you can't access it even with the reference referring the sub class instance. as that member is treated like a private member within the sub class. i.e ref.<some inherited data member > is not allowed from some third class having reference of sub class. Regards, Jolly
|
 |
subhasish nag
Ranch Hand
Joined: Apr 25, 2008
Posts: 101
|
|
Thanks Jolly for this point.Here I am only trying to mention the access within the Sub class ,but might have forgotten to mention . [ October 16, 2008: Message edited by: subhasish nag ]
|
 |
Thangaraj Selvamani
Ranch Hand
Joined: Sep 20, 2008
Posts: 61
|
|
if suppose both class in same file... it is not showing compile error...Why? EG: class A { protected int i = 10; public int getI() { return i; } } public class B extends A { public void process(A a) { a.i = a.i*2; } public static void main(String[] args) { A a = new B(); B b = new B(); b.process(a); System.out.println( b.i); } }
|
 |
Jolly Tiwari
Ranch Hand
Joined: Mar 26, 2006
Posts: 77
|
|
Within a package , a protected data member will behave very much like a data member with default access and is accessible using normal convention of .(dot) operator. Its beauty come into picture when we are giving controlled acccess to some data member across the package. Regards Jolly
|
 |
Ankit Garg
Saloon Keeper
Joined: Aug 03, 2008
Posts: 9189
|
|
also remember here that you can access protected static members of super class in sub-classes in different packages.
|
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
|
 |
 |
|
|
subject: Protected Memebres Cannot Acces In Sub class...
|
|
|