0

Hello I have question to my small program how I can print the value of p1? When I am using p1.toString() method this still shows me the address of an object I was searching in google some other ways and I still don't know how to do this. Here is the code:

public class Boss {
String name;

public Boss(String input) { // This is the constructor
    name = "Our Boss is also known as : " + input;
}

public static void main(String args[]) {
    Boss p1 = new Boss("Super-Man");

    System.out.println(p1.toString());
}
Kox
  • 98
  • 8

3 Answers3

1

You seem to have forgotten to override toString()

// Add this to Boss
public String toString() {
  return name;
}

Or (as you currently have your code),

// System.out.println(p1.toString());
System.out.println(p1.name);

You should probably add a getName() method to Boss as well,

 public String getName() {
   return name;
 }
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

You need to override the toString method to get the functionality that you are expecting. Also I recommend setting the String name to private while you're at it. If you need to provide access to the String then create a get method to return it. This prevents someone from modifying it when they shouldn't have access. Not providing an access modifier in Java defaults to protected.

public class Boss {
    private String name; // Change access modifier to private

    public Boss(String input) {
        name = "Our Boss is also known as : " + input;
    }

    @Override
    public String toString(){ // Override the toString method
        return name;
    }

    public static void main(String args[]) {
        Boss p1 = new Boss("Super-Man");
        System.out.println(p1.toString());
    }
}
Andrew_CS
  • 2,542
  • 1
  • 18
  • 38
0

The default toString() method in Object prints class name @ hash code. You can override toString() method in your class to print proper output.

@Override
public String toString(){
    return name;
}

Sources:

  1. http://javarevisited.blogspot.com/2012/09/override-tostring-method-java-tips-example-code.html
  2. http://www.geeksforgeeks.org/overriding-tostring-method-in-java/
Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58