Search code examples
javastring-conversion

Java - How can I convert an object from my own class to a string in the main class?


So, I made my own class called Guidelines, which will contain some text I want to display in a new window, when a user will press a certain button.

public class Guidelines {

    public Guidelines(String buttonName){
        guidelines(buttonName);
    }

    private String guidelines(String buttonName){
        String content = "";
        if (buttonName.equals("norman"))
            content = "Norman is the man!";
        if (buttonName.equals("nielsen"))
            content = "Nielsen is the best!";
        if (buttonName.equals("fitt"))
            content = "Fitt rocks!";
        return content;
    }
}

But when I call this class in my main class like this:

Guidelines content = new Guidelines("norman");
JTextArea textArea = new JTextArea(String.valueOf(content));

I don't get the string like "Norman is the man!", but something like uv.Guidelines@12ce0bf. I guess there's a problem in converting an object to a string. How can I get the string?


Solution

  • According to your code what you are doing is that you are defining a class with a constructor name Guidelines which take a string value and you have a method named guidelines which returns a String and takes in a string value.

    Now when you are creating a object/instance

    Guidelines content = new Guidelines("norman");
    

    it creates an Guidelines object for you and call the method guidelines(String buttonName) by passing norman. Now the constructor is being called and the constructor is calling the method but the constructor is not returning you anything. So whenever you are writing

    Guidelines content = new Guidelines("norman");
    

    the reference variable is holding the reference to the object in our case content. if you print a reference variable you will see the hashCode of that specific object in you case it is uv.Guidelines@12ce0bf.

    All you need to is that perform a call to the method guidelines(String buttonName) like that and in order to call you must declare the method as public.

    String buttonName = content.guidelines("norman);
    

    and then pass the variable buttonName

    JTextArea textArea = new JTextArea(buttonName);
    

    or you can call directly

    JTextArea textArea = new JTextArea(String.valueOf(content.guidelines("norman")));