This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
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 REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark " dobut in protected access" Watch " dobut in protected access" New topic

dobut in protected access

venkata nagarjuna

Joined: Mar 24, 2008
Posts: 7

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" 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: 15037

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 8 API documentation
Gaurav Joshi

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

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
subject: dobut in protected access
It's not a secret anymore!