gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:11:48 25 4
gpt4 key购买 nike

在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__ 的东西?如果不是,我怎样才能实现上面的输出?

最佳答案

覆盖“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());
}
}

关于java - 如何使用java通过对象名称打印类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32265811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com