gpt4 book ai didi

java - 如何更改不同类的字段值?

转载 作者:行者123 更新时间:2023-12-01 07:44:01 24 4
gpt4 key购买 nike

以下是我的练习中的引用:

The method weight queried some information from the parameter object by calling its method. It is also possible to change the state of the parameter. Add to class Reformatory the method public void feed(Person person) that increases the weight of its parameter by one.

问题是我无法想象如何在不使用练习模板中未给出的构造函数或额外参数的情况下执行此操作。

主要

public class Main {

public static void main(String[] args) {
Reformatory theReformatory = new Reformatory();

Person brian = new Person("Brian", 1, 110, 7);
Person pekka = new Person("Pekka", 33, 176, 85);


System.out.println(theReformatory.weight(brian));
theReformatory.feed(brian);
System.out.println(theReformatory.weight(brian));



}
}

public class Person {

private String name;
private int age;
private int height;
private int weight;

public Person(String name, int age, int height, int weight) {
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
}

public int getWeight() {
return this.weight;
}

public void setWeight(int weight) {
this.weight = weight;
}
}

管教所

public class Reformatory {

private int weight;


public int weight(Person person) {
weight = person.getWeight();
return weight;
}

public void feed(Person person) {
weight++;
}

}

最佳答案

与在 weight(Person person) 方法中使用 person.getWeight() 的方式相同,您可以一起使用 getWeight使用setWeight:

int newWeight = person.getWeight() + 1;
person.setWeight(newWeight);

如果您愿意,您当然也可以将其折叠为一行:

person.setWeight(person.getWeight() + 1);

关于java - 如何更改不同类的字段值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58502329/

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