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

  • 本文关键字:字段 同类 何更改 java
  • 更新时间 :
  • 英文 :


这是我练习中的一句话:

方法

权重通过调用其方法从参数对象查询一些信息。也可以更改参数的状态。将方法public void feed(Person person)添加到类感化中,该方法将其参数的权重增加 1。

问题是我无法想到如何在不使用练习模板中未给出的构造函数或额外参数的情况下做到这一点。

主要

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()的方式相同,您可以将getWeightsetWeight一起使用:

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

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

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

不要在Reformatory中声明字段weight

public class Reformatory {
public int weight(Person person) {
return person.getWeight();
}
public void feed(Person person) {
person.setWeight(person.getWeight()+1);
}
}

Java是按值传递的,在 Java 中不可能通过引用传递原语。因此,在感化类中,您应该获取人的权重,增加它并在 Person 对象中再次设置它。

在重新格式化中:

public void feed(Person person) {
person.setWeight(person.getWeight()+1);
}

你的解决方案增加了感化对象的权重,而不是人的对象的权重。

最新更新