我希望程序打印方法readA()
和readB()
的回复,但我收到来自main
的错误,指出valueB
需要String,String
因为我的构造函数GenericMemoryCell()
。但是如果我需要通过构造函数接收和存储2个参数,那么我是否必须向构造函数发送2个参数,如下所示?我怎样才能只将1个字符串分配给valueB
?
public class GenericMemoryCell<T>{
public static void main(String[] args) {
GenericMemoryCell<String> valueA = new GenericMemoryCell<String>("1", "1");
GenericMemoryCell<String> valueB = new GenericMemoryCell<String>("1");
System.out.println("storedValueA: " + valueA.readA());
System.out.println("storedValueB: " + valueB.readB());
}
public GenericMemoryCell(T storedValueA, T storedValueB)
{ this.storedValueA = storedValueA; this.storedValueB = storedValueB; writeA(storedValueA); writeB(storedValueB); }
public T readA()
{ return storedValueA; }
public T readB()
{ return storedValueB; }
private T storedValueA, storedValueB;
}
答案 0 :(得分:0)
如果要创建传递单个参数的GenericMemoryCell
,则需要添加带有单个参数的第二个构造函数。
以下是单个param构造函数的示例,它只调用两个param构造函数,为第二个值传递null:
public GenericMemoryCell(T storedValueA, T storedValueB) {
...
}
public GenericMemoryCell(T storedValueA) {
this(storedValueA, null);
}
答案 1 :(得分:0)
以下是通过使用单个参数再创建一个构造函数,仅将1个String分配给valueB:
public GenericMemoryCell(T storedValueB) {
this.storedValueB = storedValueB;
}
所以,现在你的班级如下所示。我已经编辑了一些地方来改进它。与包含两个参数的构造函数一样,无需调用:writeA(storedValueA)
和writeB(storedValueB)
。
GenericMemoryCell.java
public class GenericMemoryCell<T> {
public static void main(String[] args) {
GenericMemoryCell<String> valueA = new GenericMemoryCell<String>("1", "2");
GenericMemoryCell<String> valueB = new GenericMemoryCell<String>("3");
System.out.println("valueA (A): " + valueA.readA());
System.out.println("valueA (B): " + valueA.readB());
System.out.println("valueB (A): " + valueB.readA());
System.out.println("valueB (B): " + valueB.readB());
}
public GenericMemoryCell(T storedValueA, T storedValueB) {
this.storedValueA = storedValueA;
this.storedValueB = storedValueB;
}
public GenericMemoryCell(T storedValueB) {
this.storedValueB = storedValueB;
}
public void writeB(T storedValueB) {
this.storedValueB = storedValueB;
}
public void writeA(T storedValueA) {
this.storedValueA = storedValueA;
}
public T readA() {
return storedValueA;
}
public T readB() {
return storedValueB;
}
private T storedValueA, storedValueB;
}