定义一个汽水类java存到数组里
时间: 2023-06-10 08:07:38 浏览: 66
以下是一个汽水类的Java代码示例,同时将其存储到数组中:
```
public class Soda {
private String name;
private String brand;
private double price;
public Soda(String name, String brand, double price) {
this.name = name;
this.brand = brand;
this.price = price;
}
public String getName() {
return name;
}
public String getBrand() {
return brand;
}
public double getPrice() {
return price;
}
}
public class Main {
public static void main(String[] args) {
Soda[] sodas = new Soda[3];
sodas[0] = new Soda("Coca-Cola", "Coca-Cola Company", 1.50);
sodas[1] = new Soda("Pepsi", "PepsiCo", 1.25);
sodas[2] = new Soda("Sprite", "Coca-Cola Company", 1.25);
// Accessing a soda's properties
System.out.println(sodas[0].getName()); // Output: Coca-Cola
System.out.println(sodas[1].getBrand()); // Output: PepsiCo
System.out.println(sodas[2].getPrice()); // Output: 1.25
}
}
```
在上述示例中,我们首先定义了一个`Soda`类,它有三个属性:名称、品牌和价格。然后,我们在`Main`类中创建了一个`Soda`类型的数组,并通过构造函数将三种不同的汽水添加到数组中。最后,我们演示了如何访问每种汽水的属性。