aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Private instance variables accessed within the class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Private instance variables accessed within the class" Watch "Private instance variables accessed within the class" New topic
Author

Private instance variables accessed within the class

Arun Krishnan Nair
Greenhorn

Joined: Aug 14, 2008
Posts: 18
In the code given below, eventhough the variables i and sampleString is declared as private the same is accessable directly from the object through the main method of test class. Does it mean that private/protected declaration is ignored within the class?

public class Test {
private int i = 25;
private String sampleString = "Arun";
public static void main(String[] args) {
Test test = new Test();
System.out.println("String is --" + test.sampleString);
System.out.println("Int value is --" + test.i);
}
}


SCJP 5 - 100%
Aiming for SCBCD 5 & SCWCD 5
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

Yes! Private members are accessible to the members of the class directly and through an object of the class...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
ankit kumar
Ranch Hand

Joined: Apr 28, 2008
Posts: 108
you can't access the private member outside the class anyhow directly.


Cleared SCJP 1.5 | Cleared SCWCD 5.0
SCDJWS 6 in progress.....
sweety sinha
Ranch Hand

Joined: Jul 07, 2008
Posts: 76
yes private member is accessible in the class
Arun Krishnan Nair
Greenhorn

Joined: Aug 14, 2008
Posts: 18
yes sweety..but it was a new knowledge for me that even if create object the private variables can be accessed using . operator

Thanks for all the replies
Siri Naray
Ranch Hand

Joined: May 19, 2006
Posts: 105
Private members of a class are accessible directly to all members of a class but from static members you cannot access directly but instead can access by creating an object.

eg
class Test
{

private int x;

void getX()
{
System.out.println(x};
}
public static void main(String[] args)
{
Test t;
System.out.println(t.x); //since main is a static method
}
}
[ September 03, 2008: Message edited by: Sirisha Ghatty ]

If you worry you cannot work... If you work you need not worry
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

Originally posted by Sirisha Ghatty:

class Test
{
private int x;

public static void main(String[] args)
{
Test t;
System.out.println(Test.t); //since main is a static method
}
}


I think you were trying to write t.x instead of Test.t
Siri Naray
Ranch Hand

Joined: May 19, 2006
Posts: 105
Yup its t.x
 
 
subject: Private instance variables accessed within the class