Private instance variables accessed within the class
Arun Krishnan Nair
Greenhorn
Joined: Aug 14, 2008
Posts: 18
posted
0
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); } }
you can't access the private member outside the class anyhow directly.
Cleared SCJP 1.5 | Cleared SCWCD 5.0
SCBCD in progress.....
sweety sinha
Ranch Hand
Joined: Jul 07, 2008
Posts: 76
posted
0
yes private member is accessible in the class
Arun Krishnan Nair
Greenhorn
Joined: Aug 14, 2008
Posts: 18
posted
0
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
posted
0
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