Hi,
I am new to java and I want to know if there is a method/property for
objects that returns the name of the object that has called it.
say if I have a class for rectangle:
----------------------------------------------------------------------
public class Rectangle{
public int width;
public int height;
/* Some methods to set the width and height, find area etc*/
public void printRectangle(){
System.out.println( METHOD? + "Is having as width of"+
this.width());
}
}
------------------------------------------------------------------------
What method/property should I call in the place of "METHOD?" in
"printRectangle" above so that
If R1 is a object of Rectangle class with width 20, on calling
"R1.printRectangle()" it should print out
"R1Is having a width of 20"
Thanks,
Sai.
Gordon Beaton - 28 Feb 2007 12:13 GMT
> What method/property should I call in the place of "METHOD?" in
> "printRectangle" above so that
[quoted text clipped - 3 lines]
>
> "R1Is having a width of 20"
What should it print in the following cases?
void someMethod(Rectangle r) {
r.printRectangle();
}
Rectangle r1 = new Rectangle(...);
Rectangle r2 = r1;
r1.printRectangle();
r2.printRectangle();
someMethod(r1);
someMethod(r2);
In other words, there is no property of the object that will give you
the information you are looking for. If you want to give names to your
objects, you need to add fields to the class and should probably
override toString() as well.
/gordon

Signature
[ don't email me support questions or followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
Dimitri Kurashvili - 28 Feb 2007 14:34 GMT
if you mean class name, not the name of the object, than use
"theObject.getClass().getName()" method.
Otherwise, as gordon says, you need to define additional field with
the name of your rectangle.