• Post Reply Bookmark Topic Watch Topic
  • New Topic

Access to a private member  RSS feed

 
nirmal Rchavan
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
...
 
Olivier Houyoux
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just have a look at the Java tutorial:
http://java.sun.com/docs/books/tutorial/java/concepts/index.html
 
nirmal Rchavan
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Oliver,Wow That is such a simple solution.
i've been using this but could'nt realize it,
 
Jan van Mansum
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!