如何从类中打印属性?

时间:2017-02-14 21:56:37

标签: java

(对于记录我还是编程的新手)所以对于我的一个CS类,我们有这个项目,其中一部分是打印出类的属性而我在做这个时遇到了麻烦?我真的很感激帮助我很确定它可能很简单,但我已经挣扎了一段时间

public class Product {
private int ProductId;
private String Description;
private double Price;

public Product(int pID, String description, double price) {

    ProductId = pID;
    Description = description;
    Price = price;


}

public int getProductID() {
    return this.ProductId;

}

public void setProductID(int input) {   
    this.ProductId = input;
}



public String getDescription() {

    return this.Description;
}

public void setDescription(String DescriptionInput) {
    this.Description  = DescriptionInput;
}




public double getPrice() {
    return this.Price;
}

public void setPrice(double priceInput) {
    this.Price = priceInput;
}

}

2 个答案:

答案 0 :(得分:1)

我已经为你实现了toString方法。

public class Product {
    private int ProductId;
    private String Description;
    private double Price;

public Product(int pID, String description, double price) {

    ProductId = pID;
    Description = description;
    Price = price;


}

public int getProductID() {
    return this.ProductId;

}

public void setProductID(int input) {   
    this.ProductId = input;
}



public String getDescription() {

    return this.Description;
}

public void setDescription(String DescriptionInput) {
    this.Description  = DescriptionInput;
}




public double getPrice() {
    return this.Price;
}

public void setPrice(double priceInput) {
    this.Price = priceInput;
}

public String toString(){
  return "Product Id: "+ this.ProductId + "Description: " + this.Description + " Price: " + this.Price;
}

}

最后,只需在任何想要调用它的地方调用toString方法。

答案 1 :(得分:0)

创建一个toString()方法,以便您能够执行此操作System.out.println(Product);