Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For some reason the following code won't work when trying to create a object from different subclasses based on the result of an 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 methods on the "student" class later on in the main method it won't allow me, saying "student cannot be resolved".

like image 305
Test Avatar asked Feb 11 '23 16:02

Test


1 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);
}
like image 105
AsSiDe Avatar answered Feb 14 '23 06:02

AsSiDe