Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

protected modifier

 
Ashwin Sharma
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
When you inherit some class(It has the protected variable) in same package, instance of sub class is able to access protected variable of other instance of same class.
But if you inherit the class in other package, instance of sub class is unable to access protected variable of other instance of same class.
Why is this so?
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ranchers,


Ashwin Sharma posted November 13, 2006 01:51 AM
But if you inherit the class in other package, instance of sub class is unable to access protected variable of other instance of same class.

There should be no problem with instances of the same class extending the class with the protected member.

But the protected members are invisible in other classes extending the same class with the protected member.

e.g.
one file:


other file:


Therefore line A will compile, line B will not (protectedString not visible).


Yours,
Bu.
[ November 13, 2006: Message edited by: Burkhard Hassel ]
 
Ashwin Sharma
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Burkhard,

May be i was'nt able to explain my doubt more clearly. So let me explain it again-
package pac1;
class Super
{
protected int a;
}

package pac1;
class Sub
{
public int b;
void method()
{
Sub s = new Sub();
b = s.b;
}
}

// the above will work.

package pac1;
class Super
{
protected int a;
}

package pac2;
class Sub
{
public int b;
void method()
{
Sub s = new Sub();
b = s.b;
}
}
// this code will not work.
Access specifier works at class level, so why does it shows this type of behaviour at the instance level.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15367
40
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ashwin!

Please do not post the same question in multiple forums!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic