This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

dobut in protected access

 
venkata nagarjuna
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
venkata, please check your private messages. You can see them by clicking My Private Messages.
 
Gaurav Joshi
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 189
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic