File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Access to a private member 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 » Java » Beginning Java
Reply Bookmark "Access to a private member" Watch "Access to a private member" New topic
Author

Access to a private member

nirmal Rchavan
Ranch Hand

Joined: Jul 10, 2007
Posts: 35
Hi All,
Can you please provide me with a small code example of accessing a private member of an instance of a class by another instance of the same class.
Say we have Class Animal {
//private members
//public members
}
Class AnimalTestDrive {
public static void main(String []args) {
Animal a1 = new Animal();//object1
Animal a2 = new Animal();//object2
}
How do we have these two objects communicate with each other, may be this sounds silly but i need to clarify this..

Appretiate your help
Olivier Houyoux
Greenhorn

Joined: Oct 17, 2007
Posts: 13
Hi,

The best way to do it is to use methods to get and set the members of you class. These members should not be directly accessible from any other object.

e.g.
class Something {
private String foo;

public String getFoo() {
return foo;
}

public void setFoo(String foo) {
this.foo = foo;
}
}

Something something = new Something();
String foo = something.getFoo();
...


SCJP5
SCJD
SCMAD
Olivier Houyoux
Greenhorn

Joined: Oct 17, 2007
Posts: 13
Just have a look at the Java tutorial:
http://java.sun.com/docs/books/tutorial/java/concepts/index.html
nirmal Rchavan
Ranch Hand

Joined: Jul 10, 2007
Posts: 35
Thanks Oliver,Wow That is such a simple solution.
i've been using this but could'nt realize it,
Jan van Mansum
Ranch Hand

Joined: Oct 19, 2007
Posts: 74
A good example of an instance of a class accessing private members of another instance of the same class is a copy constructor (a constructor designed to construct a copy of another instance):


Prints: 19.

The copy constructor of p2 can access the private field of p1, which may be counterintuitive. Some people think private fields are private to an object, while in reality they are private to a class.
[ October 24, 2007: Message edited by: Jan van Mansum ]

SCJP 1.4, SCWCD 1.4
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Access to a private member
 
Similar Threads
Has-A relation
A simple class design problem
Casting reference types.
Reference Variable Casting?
enclosing class can access its inner class private members??