0

I have a basic understanding of OOP concepts, but here is a question I currently have.

Say I create this object:

Test test1 = new Test();

I then call a function within this Object

test1.toString();

And when overriding that toString() method I want to get the 'test1' object name from the main class file, so I can print it out like so...

System.out.println( "This is a test " + test1.toString() );

Prints:

This is a test test1

Thank you

3
  • 1
    Sorry i'm confused, what is your question? Commented Feb 9, 2016 at 2:37
  • You can store the 'test1' name in a private attribute and then use that value in a method. Commented Feb 9, 2016 at 2:38
  • What is the object name in Test test1 = new Test(); Test test2 = test1;? Commented Feb 9, 2016 at 2:42

1 Answer 1

4

The name of a local variable is only meaningful at compile time. There is no way to obtain the name of a reference.

Note: the reference and the Object are two different things.

What you can do is get the name of a field, however there is no way to find from an object where the object has been assigned.

The normal way to give an Object a name, is to give a field e.g. name

Test test1 = new Test("test1");
String str = test1.getName();

For enum there is an implicit name.

enum BuySell {
    Buy, Sell;
}

BuySell bs = BuySell.Buy;
String s = bs.name(); // implicitly defined for all Enum
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the help, Peter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.