File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Private variable access

 
Raj Maheshwari
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 97
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try this one with a private member but public access method:


soni
 
Raj Maheshwari
Ranch Hand
Posts: 34
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1608
 
amit taneja
Ranch Hand
Posts: 813
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic