在 if 语句中创建对象

Creating object in an if statement

我正在尝试执行以下操作:

if (vehicleType == 1){
    Car vehicle = new Car();
} else if (vehicleType == 2){
    Van vehicle = new Van();
} else  {
    Bike vehicle = new Bike();
}
vehicle.setBrand("something");

classes CarBikeVan 都扩展了 class Vehicle,其中包含 setBrand .因此 vehicle.setBrand() 总是可能的。那么为什么 IntelliJ 告诉我“找不到符号”?

注意:与 vehicle.setBrand() 相比,我对生成的对象做的更多,这就是为什么我不想在 if 语句中使用它。

此代码在 if 语句的每个分支内定义局部变量,因此它们仅作用于该块。相反,您应该 声明 if 之外的 vehicle 变量,但 初始化 它在适当的分支中:

Vehicle vehicle; // declared here
if (vehicleType == 1) {
    vehicle = new Car(); // but initialized here
} else if (vehicleType == 2) {
    vehicle = new Van(); // or here
} else  {
    vehicle = new Bike(); // or here
}
vehicle.setBrand("something");

试试这个:因为您保留了车辆,因为局部变量在您各自的条件块之外不可访问。

  Vehicle vehicle = null;
    if (vehicleType == 1){
        vehicle = new Car();
    } else if (vehicleType == 2){
        vehicle = new Van();
    } else  {
        vehicle = new Bike();
    }
    vehicle.setBrand("something");

这就是继承如此强大的确切原因。

在使用Java时,每个变量都有一个作用域,在这个作用域中他是“活着的”。 在范围内定义变量,该变量在该范围内被识别。 因此,在 IF 语句之前声明一个 Vehicle 类型的变量,将使该变量在 if 之后仍然存在。 以这种方式编程的主要原因是在编译期间,编译器不知道满足了哪些条件(如果有的话)。在不同类型中维护同名变量可能会出错。

继承使我们能够定义共同的共享行为并在我们的代码中利用该行为。 这就是为什么这里的两个例子都是正确的。

我强烈建议您阅读 java

中有关代码编译和变量范围的更多信息

https://www.geeksforgeeks.org/variable-scope-in-java/