• Post Reply Bookmark Topic Watch Topic
  • New Topic

what is the RULE behind this protected  RSS feed

 
MInu
Ranch Hand
Posts: 517
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package aa;
public class A
{
protected int x;
}

package bb;
import aa.*;
public class B extends A
{
public void test()
{ x=100;
}
}

package cc;
import bb.*;
class C extends B
{
public void test1()
{
x=1000;
}
}


is this x available in the class C ???

It is !, Then what is the RULE behind this protected ???
can any one crack this ???
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Roughly, protected members can be accessed by

1) Code in the same package as the member's class;
2) Code in subclasses of the member's class

There's actually another part of the rule, difficult to explain in a few words, which says that if there were another class D in package dd which also extended A, then D could access x in objects of type D, but not in objects of type B or C.

But in any case, you're clearly looking for examples of classes that can't access x. If you create a class E in package cc, and E makes instances of A, B, and C, it can't access the x member in any of those objects.
 
MInu
Ranch Hand
Posts: 517
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can any one give more explanation ?
 
Sanju Thomas
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My dear java gurus please give a broad answer..........
 
Robby Robson
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
whats ironic I protected is less protect than default(no access modifier)



if class A & B is in the same package and class C is a subclass of B then...

Class C CAN'T see things with default access in class B
Class C CAN see things with with protect access in Class B


I know it backwards but it shows better intentionality..



it's far more useless to see the "protected" keyword and know that it can used by subclass of package classes, than for it to mean only package classes can use it
 
Robby Robson
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
urgh typos

s/useless/usefull
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!