Home > OS >  How to return a string containing details of an instance of a class?
How to return a string containing details of an instance of a class?

Time:10-07

I am trying to use a static method to return a string containing the details of instance 'a' which is in class Person. It should return the the attributes details like Name, age etc. I used a constructor in my main class to to set the attributes. However, I am getting told I have to put the static method in my main class and when I try it does not work.

{
    public static void main(String[] args)
    {
        Person a = new Person();
        public static String getDetails(Person a)
        {
            return null;
        }
        
    }
}

Ignore the null.

CodePudding user response:

What you are trying to do is put the method getDetails() into the main method. This is not possible and will throw a compile-time error.

You can put it in the main class though, which will look like this:

public class Main {
    public static void main (String[] args) {
        // ...
    }
    
    private static String getDetails (Person p) {
        // ...
        return "";
    }
}

Seeing what the method is supposed to do though, I'd reccomend putting it in the Person class. You can Override the toString method which will also have other advantages. That'd look like this (in the Person class)

@Override
public String toString () {
    // ...
    // return detailed String
    return "";
}

This method will also be called when you use System.out.println() on an instance of this class.

CodePudding user response:

You can try generating a toString() method in Person class using your IDE(eclipse etc.). It will ask for attributes you want to include in method generation. Then you can call that method -

{
    public static void main(String[] args)
    {
        Person a = new Person();
        public static String getDetails(Person a)
        {
            return a.toString();
        }
        
    }
}
  • Related