1

I'm a newbie to Java. Can you tell me why I can't print a proper result of this code?

    public Main() {
    Pizza pizza = new Pizza("yes", "Cheese", 20000);
    System.out.println(pizza);
}

I have created the class pizza like this.

package pitjahat;

public class Pizza {
private String name;
private String topping;
private Integer price;

public Pizza(String name, String topping, Integer price) {
    super();
    this.name = name;
    this.topping = topping;
    this.price = price;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getTopping() {
    return topping;
}
public void setTopping(String topping) {
    this.topping = topping;
}
public Integer getPrice() {
    return price;
}
public void setPrice(Integer price) {
    this.price = price;
}
}

and the result that comes out when I run is like this

pitjahat.Pizza@52af6cff
sashimi
  • 1,224
  • 2
  • 15
  • 23
JEPPUNG
  • 23
  • 4
  • 2
    You need to create a `toString()` method in the Pizza class for println to be able to print it properly – Nosrep Oct 22 '20 at 12:45
  • 5
    Does this answer your question? [How do I print my Java object without getting "SomeType@2f92e0f4"?](https://stackoverflow.com/questions/29140402/how-do-i-print-my-java-object-without-getting-sometype2f92e0f4) – OH GOD SPIDERS Oct 22 '20 at 12:45

1 Answers1

0

You have to override/implement the toString() method in your Pizza class.

If you use Intellij IDEA you can use the Alt + Insert combo to generate the method by the intellij. (Or Right click -> Generate...)

In eclipse Right click -> Source -> Generate toString()

This will help you:

https://www.javatpoint.com/understanding-toString()-method

stackstack293
  • 341
  • 3
  • 12