我有一个有几个成员的 Java 类。我想为它写一个自定义演员表。我想知道怎么可能这样做?
让我们假设类如下:
class Person {
private int age;
private float weight;
// getters and setters and etc
}
我希望int强制转换返回age一个对象的成员,并希望强制转换float返回一个对象的成员weight。
例如:
public class Main {
public static void main(String[] args) {
// create an object
Person P = new Person();
P.setAge(21);
P.setWeight(88.0);
// case 1: casting object to an existing data type
int personAge = (int) P; // would return the age
float personWeight = (float) P; // would return the weight
// case 2: casting an existing data type to an object
Person P2 = (Person) personAge; // this would create an instance of the object whose age is assigned and weight is not assigned
}
}
我想知道是否可以做相反的事情。特别是,强制转换int为将返回其已分配Person的实例,对于.Personagefloat
我知道这个问题可能没有答案。但是因为我在搜索中没有找到任何有用的结果,所以我决定问问它。
PS 我知道对于 a String,该toString方法会处理案例 1。
手掌心
慕标5832272
12345678_0001
相关分类