简体   繁体   English

如何从if-else语句创建/实例化对象?

[英]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-else语句的结果从不同的子类创建对象时,以下代码将不起作用:

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. student变量是在if/else范围内声明的,不在外面,因此你不能在这些代码块之外使用它。

If UndergradTA and GradTA have a common super class or interface, then declare the variable outside and use it accordingly: 如果UndergradTAGradTA有一个共同的超类或接口,那么在外面声明变量并相应地使用它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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