javasubclasslow-level-code

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. Can someone please tell me where I am messing up? Thanks!


Solution

  • 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");