How can I create / create an instance of an object from an if-else statement?

For some reason, the following code will not work when trying to create an object from different subclasses based on the result of the if-else statement:

if (option == 1) {

     UndergradTA student = new UndergradTA();
     student.setIsUnderGrad(true);

} else if (option == 2) {

     GradTA student = new GradTA();
     student.setIsGrad(true);
}

When I then try to use the methods in the student class later in the main method, this will not allow me to say that the student cannot be allowed.

+4
source share
2 answers

Change your code to:

UndergradTA student = null;
GradTA stud = null;

if (option == 1) {

    student = new UndergradTA();
    student.setIsUnderGrad(true);

} else if (option == 2) {

    stud = new GradTA();
    stud.setIsGrad(true);
}
+5
source

studentvariable is declared within the scope if/else, not outside, so you cannot use it outside of these blocks of code.

UndergradTA GradTA , :

Student student = null;
if (option==1) {
    student = new UndergradTA();
    //cumbersome
    student.setIsUnderGrad(true);
} else if(option==2) {
    student = new GradTA();
    //cumbersome
    student.setIsGrad(true);
}
student.someMEthod(...);
+2

All Articles