如何使用java通过对象名称打印类的属性?

时间:2015-08-28 07:42:03

标签: java python

在Python中,如果要打印类属性的字符串表示,则可以定义类似

的内容。
class building:
   def __init__(self,type,height):
       self.type = type
       self.height = height

    def __str__():
        return "i am a %s and i am {:%.1f} meters tall", (type,height)

hospital = Building()
hospital.type = "Medical Facility"
hospital.height = 30

print(hospital)
>>> i am a Medical Facility and i am 30.0 meters tall

java是否具有python __str__的等价物?如果不是,我怎样才能实现上面的输出?

1 个答案:

答案 0 :(得分:1)

覆盖“toString()”。我认为它与python中的 str()相同

public class Employee {
    public int id;
    public String fName;
    public String mName;

public Employee(int id, String fName, String mName) {
    this.id = id;
    this.fName = fName;
    this.mName = mName;
}




@Override
public String toString() {
    String output = "Hello, I am employee " + id + ", my first name is " + fName + " and my middle name is " + mName;
    return output;
}


public static void main(String[] args) {
    Employee e= new Employee(1, "foo" ,"bar");
    System.out.println(e.toString());
}
}