aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Private variable access Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Private variable access" Watch "Private variable access" New topic
Author

Private variable access

Raj Maheshwari
Ranch Hand

Joined: Jul 02, 2004
Posts: 34
While playing the javaranch game I came across a question:

Can one object access a private variable of another object of the same class?

I selected no and the applet came back saying the answer is yes:

I coded up the following:
-------------------------

public class Test1 {

public static void main(String[] args) {

Test2 t1 = new Test2();
Test2 t2 = new Test2();
t2.i = t1.i; // Illegal
}
}

class Test2{

private int i;

}

--------

Note the line t2.i=t1.i
I cant compile it.

Test1.java:21: i has private access in Test2
t2.i = t1.i;
^
Test1.java:21: i has private access in Test2
t2.i = t1.i;
^
2 errors

Am I missing the point here?

Thanks
Raj
Soni Prasad
Ranch Hand

Joined: Mar 09, 2005
Posts: 97
try this one with a private member but public access method:


soni


SCJP 1.4, SCBCD 1.3
Raj Maheshwari
Ranch Hand

Joined: Jul 02, 2004
Posts: 34
Hi Soni

I tried the following and it (expectedly) works as well.

---------

public class Test1 {

public static void main(String[] args) {
int i;
Test2 t1 = new Test2();
Test2 t2 = new Test2();

i=t1.getI();
System.out.println(i);
}
}

class Test2{

private int i=2;

public int getI(){
return i;
}

}

----------

I can access i which is private in Test 1 simply because I am calling a public method on Test2. Test2.getI of course will have access to i.

The original question was that can 2 instances of a class access each others private variables?
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Try this:
http://qa.jtiger.org/GetQAndA.action?qids=17


Tony Morris
Java Q&A (FAQ, Trivia)
amit taneja
Ranch Hand

Joined: Mar 14, 2003
Posts: 810
hey raj

you can only access private variable only from that class its self

you are trying to access the private variable from other class even from the object that carries pvt variable ..but you can't call like that...

you can only call through public method...

and same ..you can't call the pvt method from another class but only from that classs itself


Thanks and Regards, Amit Taneja
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Private variable access