• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Doubts on Protected Members

 
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I have a class pack in a package packed as follows

package packed;
public class pack
{
static public int x1 = 7;
static protected int x2 = 8;
static int x3=9;
static private int x4 =10;
}
An other class Test in a different package
import packed.pack;
class test extends pack
{
public static void main( String args[] )
{
pack p = new pack();
System.out.println( pack.x2 );
}
}

If i remove static from protected variable x2, i am getting a compiler error that x2 is not visible.Why is it so?

As per the API, i should be able to access the protected variables in or outside the package using inheritance.
 
Ranch Hand
Posts: 179
Mac Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi jammy,
you are now accessing the variable in a static way so if you remove static it is going to give a compile error. So if you need to access x2 then using the instance p should help.
It is going to be something like p.x2

Hope this explains the question
 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi,
If you remove static modifier to variable x2 then it becomes a instance member,you cannot access a instance member using a class name.In that case you can access x2 using reference p as long as x2 is static only.Because
you can access protected members in a different package only through inheritance but you cannot access them by creating a reference to that class.In that case you can access only static members but you cannot access instance members by using references.
[ March 23, 2008: Message edited by: Naveen kumar ]
 
machines help you to do more, but experience less. Experience this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic