简体   繁体   中英

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".

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);
}

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

If UndergradTA and GradTA have a common super class or interface, then declare the variable outside and use it accordingly:

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(...);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM