我正在使用方法鏈接編寫DerivedClass(extends SuperClass)。例如,Java:派生類中的方法鏈接
public class SuperClass {
protected int responseCode;
protected String responseMessage;
public void setResponseCode(int code) {
this.responseCode = code;
}
public int getResponseCode() {
return responseCode;
}
public SuperClass withResponseCode(int code) {
setResponseCode(code);
return this;
}
public void setResponseMessage(String message) {
this.responseMessage = message;
}
public String getResponseMessage() {
return responseMessage;
}
public SuperClass withResponseMessage(String message) {
setResponseMessage(message);
return this;
}
}
而且
public class DerivedClass extends SuperClass {
protected String credentialType;
protected String credentialId;
public void setCredentialType(String type) {
this.credentialType = type;
}
public String getCredentialType() {
return credentialType;
}
public DerivedClass withCredentialType(String type) {
setCredentialType(type);
return this;
}
public void setCredentialId(String id) {
this.credentialId = id;
}
public String getCredentialId() {
return credentialId;
}
public DerivedClass withCredentialId(String id) {
setCredentialId(id);
return this;
}
public static void main(String[] args) {
DerivedClass dc = new DerivedClass();
/*dc.setResponseCode(200);
dc.setResponseMessage("SUCCESS");
dc.setCredentialType("MobileIdentifier");
dc.setCredentialId("678882");*/
dc.withResponseCode(200)
.withResponseMessage("SUCCESS")
.withCredentialType("MobileIdentifier")
.withCredentialId("678882");
System.out.println("Derived Class: Code - " + dc.getResponseCode() + " - Response Message - " + dc.getResponseMessage() + " - Credential Type - " + dc.getCredentialType());
}
}
在上述的彙編我越來越:
DerivedClass.java:41: error: cannot find symbol
.withCredentialType("MobileIdentifier")
^
symbol: method withCredentialType(String)
location: class SuperClass
1 error
爲什麼我收到這個時CredentialType DerivedClass中的字段而不是SuperClass中的字段?如何使用DerivedClass對象鏈接SuperClass & DerivedClass的混合方法?
因爲你對'withResponseMessage'的調用返回一個'SuperClass','SuperClass'沒有'withCredentialType'方法。 – csmckelvey
它有它 - publicResponseClassResponseMessage(String message) –
這不是我正在談論的那個。該方法返回一個'SuperClass',然後你嘗試在返回的對象上調用'withCredentialType'方法,因爲該方法**在'SuperClass'中不存在**。 – csmckelvey