在将具体事物封装成类时,我们需要将共有的属性提炼出来,也就接下来介绍的成员变量。
例如,我们封装了一个Car
类,并给其添加了 3 个成员变量brand
、color
以及price
。每一个Car
实例都具备这 3 个成员变量,可以对其进行赋值和引用,具体请看示例:
public class Car {
// Members of Car Class
String brand;
String color;
long price;
public static void main(String[] args) {
Car benz = new Car();
benz.brand = "Benz";
benz.color = "Red";
benz.price = 400000;
}
}
🔔 成员变量在类实例化后,便会有初始值,其特性与之前介绍的数组几乎一样
如果我们实例化了多个Car
类,那么也可以将其存储成数组的形式:
public class Car {
String brand;
String color;
long price;
public static void main(String[] args) {
Car benz = new Car();
benz.brand = "Benz";
benz.color = "Red";
benz.price = 400000;
Car bmw = new Car();
bmw.brand = "BMW";
bmw.color = "White";
bmw.price = 420000;
Car[] cars = {benz, bmw};
for (Car car: cars) {
System.out.println(car.brand + "-" + car.color + "-" + car.price);
}
}
}