Java:如何填充子类中的变量?
问题描述:
所以这不是一个任务,但我的讲座幻灯片没有说清楚,当我尝试编写类似的代码时,我遇到了一个问题。Java:如何填充子类中的变量?
我无法弄清楚如何填充我的子类中的变量。
这里是我的测试代码迄今:
实现类:
import javax.swing.JOptionPane;
公共类府{
/**
* @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());
}
}
超类:
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;
}
}
子类:
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();
}
}
当我尝试运行代码,如果我试图插入式类数据转换成的setType()方法,它会给我一个错误。有人可以告诉我我在哪搞乱吗?谢谢!
答
记得原来指针:
if(option==0){
type t = new type();
t.setSize(25);
t.setType("Bedroom");
r[count]= t;
}
另外,您可以转换为原始类型:
((type) r[count]).setType("Bedroom");