简体   繁体   中英

How to return the name of the instance of a class in Java

I am a beginner in Java (and programming), and there should be a simple answer to this, but I could not find it. I want to write a code that would print the value of the reference name of an instance variable. For example:

Public class Person {
    Person() {
        //attributes, height, weight, etc.
    }

    Person Person1 = new Person();
}

I would like to write a line of code that would produce something to the tune of

"The attribute of Person1 is..."

Something to the tune of System.out.println("The attribute of Person1 " +( ???? )+" is ....")

I was unable to find or create a method that would return the name Person1.

"Person1" is not the name of the instance, but instead is the name of a variable that holds the reference to the instance. The instance itself has no name. You will have to give it an attribute of name if you care to keep it.

public class Person {
   private final String name;
   public Person(String name) {
      this.name = name;
   }

   public String getName() {
       return this.name;
   }
}

then you can do:

Person person1 = new Person("Jeff");

System.out.println("Person1's name is: " + person1.getName());

The output of that will be:

Person1's name is: Jeff

It is not generally possible to do exactly what you want. I don't think variable names are even compiled into the classes.

It can be done with compile time annotations but it's not trivial.

To be able to do that you should override the toString() function Something like this

/* Returns the string representation of your class object .*/
     @Override
        public String toString() {
            return "The attributes of this person are :height - " + height + " weight - " + weight  + // you are print out all your properties. 
        }

Now whenver you want to print the object you can do

System.out.println(person1);

I'm not sure how familiar you are with programming languages in general. I see you say you are new to Java, so I'll start there. Java, like many object-oriented languages, uses inheritance when you create classes. In Java, when you define a class you can use the "extends" keyword to sub-class and use or override any methods in the parent class. Now, in Java, ALL classes automatically inherit from this class called Object.

This is very useful to know, because Object contains a few useful methods, most notably of them is "toString()". You do not need to use extends to get these methods btw. Now, toString on its own is not useful, but you can override it to print out what you want.

public class Person
{
    String name;
    int age;

    Person(String name, int age)
    {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString()
    {
        return "Name is: " + name + "and age is: " + age";
    }
}

Notice the toString() method I defined there? Anytime you call this method on an object, you will get that string printed out. So for instance, in your example:

Person person1 = new Person("Ford Prefect", 42);

System.out.println(person1.toString()); //Will print what we defined in toString.

You don't even need the .toString(), just person1 because the JVM will realize you meant to use toString. If you use IntelliJ IDE, you can do Alt + Insert and select toString() to override it. IDEs are wonderful tools to help you be more efficient. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM