在Java中,如果多个类有共同的字段,可以通过以下几种方式使用它们的组合:
通过继承,子类可以继承父类的字段和方法。
class CommonFields {
protected String commonField1;
protected int commonField2;
public CommonFields(String commonField1, int commonField2) {
this.commonField1 = commonField1;
this.commonField2 = commonField2;
}
}
class SubClass extends CommonFields {
private String specificField;
public SubClass(String commonField1, int commonField2, String specificField) {
super(commonField1, commonField2);
this.specificField = specificField;
}
public void display() {
System.out.println("Common Field 1: " + commonField1);
System.out.println("Common Field 2: " + commonField2);
System.out.println("Specific Field: " + specificField);
}
}
通过组合,一个类可以包含另一个类的实例,从而共享字段。
class CommonFields {
protected String commonField1;
protected int commonField2;
public CommonFields(String commonField1, int commonField2) {
this.commonField1 = commonField1;
this.commonField2 = commonField2;
}
}
class SubClass {
private CommonFields commonFields;
private String specificField;
public SubClass(String commonField1, int commonField2, String specificField) {
this.commonFields = new CommonFields(commonField1, commonField2);
this.specificField = specificField;
}
public void display() {
System.out.println("Common Field 1: " + commonFields.commonField1);
System.out.println("Common Field 2: " + commonFields.commonField2);
System.out.println("Specific Field: " + specificField);
}
}
通过接口,可以定义一组共同的字段和方法,然后让多个类实现这个接口。
interface CommonFieldsInterface {
String getCommonField1();
int getCommonField2();
}
class SubClass implements CommonFieldsInterface {
private String commonField1;
private int commonField2;
private String specificField;
public SubClass(String commonField1, int commonField2, String specificField) {
this.commonField1 = commonField1;
this.commonField2 = commonField2;
this.specificField = specificField;
}
@Override
public String getCommonField1() {
return commonField1;
}
@Override
public int getCommonField2() {
return commonField2;
}
public void display() {
System.out.println("Common Field 1: " + getCommonField1());
System.out.println("Common Field 2: " + getCommonField2());
System.out.println("Specific Field: " + specificField);
}
}
private
修饰符和提供公共的getter/setter方法来解决。通过以上方法,你可以根据具体的需求选择合适的方式来使用共同的字段。
领取专属 10元无门槛券
手把手带您无忧上云