aspose file tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes problem related modifier Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "problem related modifier "protected"" Watch "problem related modifier "protected"" New topic
Author

problem related modifier "protected"

Palash Kumar
Ranch Hand

Joined: Jul 21, 2009
Posts: 33

package packed;
public class pack
{
static public int x1 = 7;
static protected int x2 = 8;
static int x3=9;
static private int x4 =10;
}

________________________________________________

import packed.pack;
class test extends pack
{
public static void main( String args[] )
{
pack p = new pack();
System.out.println( pack.x2 );
}
}


this is giving output "8". But if i removes static modifier from x2, there is an error. Please explain


SCJP 6 with 80%, going for SCWCD
Abhijeet Pathak
Ranch Hand

Joined: Jul 05, 2009
Posts: 33
Obviously there will be an error. When you remove "static" x2 becomes an instance variable (can be accessed only with object) and you cannot access it with class name.
It has nothing to do with "protected" access modifier.


I am the one who knows that I don't know anything.
Abhijeet
Mo Jay
Ranch Hand

Joined: Feb 16, 2009
Posts: 83
Ok, you have 2 ways how to access x2 here; either keep static keyword and you can access it directly because you have copy of x2 inherited in your testpack class anyways. Or you can remove the static keyword then use an instance of testpack class to access the inherited copy of x2, check below for sample:

Either:
in pack:
in testpack:

OR:
in pack:
in testpack:



You can also use some getter method if you want but I don't think this is the main question here.

Cheers!!!
Ankit Garg
Saloon Keeper

Joined: Aug 03, 2008
Posts: 9189
    
    2

Palash, since x2 is protected, so class test can only access it through inheritance. So if you make it non-static, and try to access it through an instance of pack class, then you'll get an error





Also when you post a source code, use code tags to make the code readable...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Palash Kumar
Ranch Hand

Joined: Jul 21, 2009
Posts: 33

Thank you all.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel/download
 
subject: problem related modifier "protected"
 
Similar Threads
scope question
Protected Modifier Question
Doubts on Protected Members
accessability about protected instances
inquisition question