Java 如何在obj上使用集合方法。更改值的引用
你好。一般来说,我对Java和OOP不太熟悉,但在Python和C中还可以。我需要了解如何在餐厅对象引用r2上使用适当的mutator(setter)方法,并将服务人数和人均价格的值更改为餐厅对象引用r1中的相同值。我不想更改餐厅名称。 餐厅等级:Java 如何在obj上使用集合方法。更改值的引用,java,setter,Java,Setter,你好。一般来说,我对Java和OOP不太熟悉,但在Python和C中还可以。我需要了解如何在餐厅对象引用r2上使用适当的mutator(setter)方法,并将服务人数和人均价格的值更改为餐厅对象引用r1中的相同值。我不想更改餐厅名称。 餐厅等级: package restaurantclient; public class RestaurantClient { public static void main(String[] args) { Restaurant r1 = n
package restaurantclient;
public class RestaurantClient {
public static void main(String[] args) {
Restaurant r1 = new Restaurant("McDonalds", 1000000, 8.00);
Restaurant r2 = new Restaurant("KFC", 500000, 6.00);
System.out.println(r1.toString());
System.out.println(r2.toString());
//I would like the code to go here, in-between the toString and the equals comparison.
if (r1.equals(r2)) {
System.out.println("The objects are equal.");
}
else {
System.out.println("The objects are not equal.");
System.out.println();
}
System.out.println();
System.out.print("The avg. annual taxes paid by restaurant 1 is: $");
System.out.println(r1.getAverageTaxes());
System.out.print("The avg. annual taxes paid by restaurant 2 is: $");
System.out.println(r2.getAverageTaxes());
System.out.println();
}
}
您已经在类上定义了setter方法-
r2.setAveragePrice(r1.getAveragePrice());
r2.setPeopleServed(r1.getPeopleServed());
至于你的问题——
在餐厅对象参考r2上使用适当的mutator(setter)方法,并将服务人数和人均平均价格的值更改为餐厅对象参考r1中的相同值
首先,使用getter方法检索r1
对象的值,然后将这些值传递给r2
对象上的setter方法。例如—
//Setters (Mutators)
public void setPeopleServed(int peopleServed) {
this.peopleServed = peopleServed;
}
public void setAveragePrice(double averagePrice) {
this.averagePrice = averagePrice;
}
或者,更简洁地说:
int peopleToSet = r1.getPeopleServed();
r2.setPeopleServed(peopleToSet);
您已经在类上定义了setter方法-
r2.setAveragePrice(r1.getAveragePrice());
r2.setPeopleServed(r1.getPeopleServed());
至于你的问题——
在餐厅对象参考r2上使用适当的mutator(setter)方法,并将服务人数和人均平均价格的值更改为餐厅对象参考r1中的相同值
首先,使用getter方法检索r1
对象的值,然后将这些值传递给r2
对象上的setter方法。例如—
//Setters (Mutators)
public void setPeopleServed(int peopleServed) {
this.peopleServed = peopleServed;
}
public void setAveragePrice(double averagePrice) {
this.averagePrice = averagePrice;
}
或者,更简洁地说:
int peopleToSet = r1.getPeopleServed();
r2.setPeopleServed(peopleToSet);
由于您没有显示Restaurant类有哪些方法,所以不确定您在问什么-如何编写setter方法?Restaurant的定义是什么?它是否为这些字段设置了一个方法,如果没有,您需要在restaurant类中创建这些方法。好的,我已经上传了restaurant类。再次感谢您的帮助。由于您没有显示Restaurant类有哪些方法,所以不确定您在问什么-如何编写setter方法?Restaurant的定义是什么?它是否为这些字段设置了一个方法,如果没有,您需要在restaurant类中创建这些方法。好的,我已经上传了restaurant类。再次感谢你的帮助。