在 Java 中,我们可以通过构造方法或普通方法来初始化属性成员 fuelTypefuelPrice

  1. 使用构造方法进行初始化:
public class Car {
    private String fuelType;
    private double fuelPrice;

    public Car(String fuelType, double fuelPrice) {
        this.fuelType = fuelType;
        this.fuelPrice = fuelPrice;
    }

    // 其他属性和方法...

    public static void main(String[] args) {
        Car car = new Car('Petrol', 1.5); // 使用构造方法初始化
        // ...
    }
}
  1. 使用普通方法进行初始化:
public class Car {
    private String fuelType;
    private double fuelPrice;

    public void initFuelPrice() {
        this.fuelType = 'Petrol';
        this.fuelPrice = 1.5;
    }

    // 其他属性和方法...

    public static void main(String[] args) {
        Car car = new Car();
        car.initFuelPrice(); // 调用初始化方法
        // ...
    }
}

无论使用构造方法还是普通方法进行初始化,都可以根据具体需求选择适合的方式。

Java 初始化属性成员 fuelType 和 fuelPrice 的两种方法

原文地址: https://www.cveoy.top/t/topic/exOH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录