我试图通过创建一个新类 (Refactor.java) 来减少代码重复,以容纳在其他两个类(A 和 B)中调用的方法。
这是我到目前为止想出的:
public class Refactor {
protected int code; // code
protected String companyName; // company name
protected String email; // email of the company
protected String type; // type
protected double price; // price
// gets and sets
public int getCode() {
return code;
}
public void setCode(int c) {
this.code = c;
}
public String getCompanyName(){
return companyName;
}
public void setCompanyName(String cn) {
this.companyName = cn;
}
public String getEmail(){
return email;
}
public void setEmail(String em) {
this.email = em;
}
public String getType(){
return type;
}
public void setType(String t) {
this.type = t;
}
public double getPrice(){
return price;
}
public void setPrice(double p) {
this.price = p;
}
}
在 A 类中,“accData.getSomething()”方法似乎没问题,但所有“accData.setSomething()”方法都给我以下错误:“Refactor 类型中的方法 setCode(int) 不适用于参数 ()".
这是我目前在 A 课上的内容:
import java.util.ArrayList;
public class Accommodation
{
protected static int MAX_NUM_TOURS = 3; // maximum number of tours defined by the hotel regulation bodies
protected int code; // code
protected String companyName; // company name
protected String email; // email of the company
protected String type; // type
protected double price; // price
protected String city; // city of the accommodation
protected int numberBeds; // number of beds
/**
* Constructor
* @param c code
* @param cn company name
* @param em email of the company
* @param t type (hotel, hostel, bnb, ...)
* @param p price
* @param ct city of the accommodation
* @param nb number of beds
*/
public Accommodation(int c, String cn, String em, String t, double p, String ct, int nb) {
this.code = c;
this.companyName = cn;
this.email = em;
this.type = t;
this.price = p;
this.city = ct;
this.numberBeds = nb;
}
//this is where I'm trying to call the Refactor class
public static void AccData() {
Refactor accData = new Refactor();
accData.getCode();
accData.setCode();
accData.getCompanyName();
accData.setCompanyName();
accData.getEmail();
accData.setEmail();
accData.getType();
accData.setType();
accData.getPrice();
accData.setPrice();
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getNumberBeds() {
return numberBeds;
}
public void setNumberBeds(int numberBeds) {
this.numberBeds = numberBeds;
}
}
为什么我会收到那个错误?我该如何解决这个问题?
我尝试谷歌搜索如何重构代码,发现这个堆栈溢出问题与我的相似。然而,我不太明白给出的答案,因此我为什么要再次提问。
我期望能够通过调用 Refactor 类中的这些方法来避免代码重复。
如果你有这样的课程:
class A {
// ...
public void setCode(int param) {
// ...
}
}
你可以这样调用setCode方法:
A a = new A();
a.setCode(1);
a.setCode(2);
但是你可以。像这样调用方法 setCode:
A a = new A();
a.setCode();