我正在使用方法链编写DerivedClass(扩展SuperClass)。例如,
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中的字段时,为什么会出现这种情况?如何从SuperClass& amp; DerivedClass使用DerivedClass对象?
答案 0 :(得分:3)
正如其他人所说的那样,您收到了编译错误,因为SuperClass
的方法会返回SuperClass
类型,而DerivedClass
类型不包含SuperClass
'方法。
解决此问题的正确方法是使SuperClass
抽象并在public abstract class SuperClass<T extends SuperClass<T>> {
// TODO attributes, getters and setters
public T withResponseCode(int code) {
setResponseCode(code);
return (T) this; // this cast is absolutely safe!
}
// TODO other SuperClass builder methods
}
上使用带有递归类型的泛型(也称为F-bound type):
DerivedClass
然后,您可以按如下方式定义public class DerivedClass extends SuperClass<DerivedClass> {
// TODO attributes, getters and setters
public DerivedClass withCredentialType(String type) {
setCredentialType(type);
return this;
}
// TODO other DerivedClass builder methods
}
:
SuperClass
并且不会再出现编译错误。这种方法的缺点是它强制你使jsonconvert.serializeobject
类抽象,以便只使用派生类。
答案 1 :(得分:1)
方法withReponseMessage()
返回SuperClass
类型的对象。
类SuperClass
没有名为withCredentialType()
的方法,这就是您收到错误消息的原因。
解决此问题的一个策略是使SuperClass
抽象,然后在那里定义所有API方法,即使这些方法是抽象的。否则,您将必须转换从第一个方法调用返回的对象(这可能使您的程序在将来容易受到不匹配异常的影响。
答案 2 :(得分:1)
您需要将其向下转换为DerivedClass
,或者从头开始使用DerivedClass
实例。