aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes  dobut in protected access Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark " dobut in protected access" Watch " dobut in protected access" New topic
Author

dobut in protected access

venkata nagarjuna
Greenhorn

Joined: Mar 24, 2008
Posts: 7
hi,

please clarify the dobut regarding protected. see the code below

package p1;
public class demo1
{
protected int i;
}
-------------
package p2;
import p1.demo1;
class demo2 extends demo1
{
public static void main(String args[])
{
System.out.println(new demo2().i);//line 1
}
}

this is working fine....but if i change line 1 to "new demo1().i" from "new demo2().i" ....it is generating compiler error..

but when the two classes belong to same package there was no problem.

protected variables or methods can be accessed by the subclasses even though if they were in different package .

just help me from this issue..

[ March 27, 2008: Message edited by: venkata ]
[ March 27, 2008: Message edited by: venkata ]
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13884
    
  10

venkata, please check your private messages. You can see them by clicking My Private Messages.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Gaurav Joshi
Greenhorn

Joined: Mar 08, 2008
Posts: 18
You just answered your own query, if classes are in different packages, then protected members can only be accessed by subclasses, in your example main method is in the same class(demo2) hence can access i.
Mamadou Touré
Ranch Hand

Joined: Dec 27, 2007
Posts: 189
hi,

That's a normal behavior. Remeber this : Subclasses outside the package CAN'T USE A SUPERCLASS REFERENCE to access a protected member (as said at page 36 of the scjp 5 book of Kathy sierra and Bert Bates).

Hope this will help


SCJP 5 (76%)
SCWCD 5 (86%)
SCBCD 5(70%)
--------------------
"The greatest glory in living lies not in never falling, but in raising every time we fall.".. Nelson Mandela
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: dobut in protected access
 
Similar Threads
Dobut in equals method
why compile time error???
compound assignment operator behaving differently for Byte and byte
Running unix command using java shows error
Doubt about protected