Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

accessing private variable of another object of same class

 
anil bisht
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can one object access a private variable of another object of same class...
the answer says yes ... how ???
i saw this answer somewhere in this discussion forum..
so please if someone could answer it or send me the link to that discussion ..
TIA
anil
 
Bosun Bello
Ranch Hand
Posts: 1511
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As long as they are object of the same classes and not object of subclasses, I don't see why not. It's easier to fire up your compiler to test these kinds of things. I can't remember where I saw this inthis forum. I believe was a similar question in the "rules round up" game
Bosun
 
Sahir Shah
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmmmm. Can be tricky. I'll give it a shot anyway.
<pre>
class Rectangle{
private int width , length;
public Rectangle(int w , int l)
{
width = w;
length = l;
}
public int getArea()
{
return width * length;
}
private void setSize(int w , int l)
{
width = w;
length = l;
}
public void clone(Rectangle rectangle)
{
rectangle.setSize(this.width , this.length);
}
}
public class SameClassObject{
public static void main(String[] args)
{
Rectangle r1 = new Rectangle(10,10);
System.out.println(r1.getArea());
Rectangle r2 = new Rectangle(20,20);
r2.clone(r1);
System.out.println(r1.getArea());
}
}
</pre>

Cheers
Sahir
oops. sorry. I keep forgetting to close the pre tag.

[This message has been edited by Sahir Shah (edited December 09, 2000).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic