[英]Java: How to populate a variable in subclass?
So this is not a assignment but one of my lecture slide did not make it clear and when I try to code something similar myself, I run into a problem. 因此,这不是一项任务,但是我的演讲幻灯片之一并没有清楚说明,当我尝试自己编写类似的代码时,我遇到了问题。
I can't figure out how to populate a variable that is in my subclass. 我不知道如何填充子类中的变量。
here's my test code thus far: 到目前为止,这是我的测试代码:
Implementation class: 实现类:
import javax.swing.JOptionPane;
public class House { 公共类房屋{
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int count = 0;
room[] r = new room[3];
int option = JOptionPane.showConfirmDialog(null, "type");
if(option==0){
r[count]=new type();
r[count].setSize(25);
r[count].setType("Bedroom");
}
else if(option==1){
r[count] = new room();
r[count].setSize(25);
}
JOptionPane.showMessageDialog(null, r[count].toString());
}
} }
Superclass: 超类:
public class room {
double size;
public room(){
}
public room(double size){
this.size=size;
}
public double getSize(){return this.size;}
public boolean setSize(double size){
if(size<0.0){
return false;
}
else{
return true;
}
}
public String toString(){
return "Room size: " + this.size;
}
} }
Subclass: 子类:
public class type extends room {
String type;
public type(){
}
public type (double size, String type){
super(size);
this.type=type;
}
public String getType(){return this.type;}
public boolean setType (String type){
if(type.equals("")){
return false;
}
else{
return true;
}
}
public String toString(){
return super.toString() + "Room Type: " + this.getType();
}
} }
when i try to run the code, if I tried to insert data into setType() method in type class, it would give me an error. 当我尝试运行代码时,如果尝试将数据插入类型类的setType()方法中,则会给我一个错误。 Can someone please tell me where I am messing up?
有人可以告诉我我在搞砸吗? Thanks!
谢谢!
Remember the original pointer: 记住原始指针:
if(option==0){
type t = new type();
t.setSize(25);
t.setType("Bedroom");
r[count]= t;
}
Alternatively you can cast to original type: 或者,您可以强制转换为原始类型:
((type) r[count]).setType("Bedroom");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.