method to access the name of the object that got created.

S

Saiprasad

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.
 
G

Gordon Beaton

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"

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
 
D

Dimitri Kurashvili

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top