引言
在Java编程中,理解类的继承、封装和多态是至关重要的。本文将通过一个具体的案例——“凯越”和“君威”汽车销售系统,深入解析Java编程中的关键概念。
案例背景
假设我们正在开发一个汽车销售系统,其中包含两种车型:“凯越”和“君威”。我们需要实现以下功能:
- 管理库存,确保销售时不会超出库存数量。
- 显示当前销售情况,包括每种车型的销售数量。
类的设计
为了实现上述功能,我们将设计几个类,包括Car
、Saler
和Main
。
Car类
public class Car {
private String type;
private String id;
public Car(String type, String id) {
this.type = type;
this.id = id;
}
public String getType() {
return type;
}
public String getId() {
return id;
}
}
Saler类
import java.util.ArrayList;
import java.util.List;
public class Saler {
private List<Car> cars;
public Saler() {
cars = new ArrayList<>();
}
public void addCar(Car car) {
if (car.getType().equals(type0 ? "凯越" : "君威") && !exists(cars, car)) {
cars.add(car);
}
}
public void printStockInfo(int num, int type0) {
int c = 0;
for (Car car : cars) {
if (car.getType().equals(type0 ? "凯越" : "君威")) {
c++;
}
}
if (c < num) {
System.out.printf("库存不足 , 实际售出 %s %d 辆\n", type0 ? "凯越" : "君威", num);
} else {
System.out.printf("售出 %s %d 辆\n", type0 ? "凯越" : "君威", num);
}
}
public void printSalesInfo() {
System.out.println("当前销售情况一览");
System.out.printf("%10s%10s\n", "汽车款式", "汽车编号");
for (Car car : cars) {
System.out.printf("%10s%10s\n", car.getType(), car.getId());
}
System.out.println("---------------------------");
System.out.printf("小计:%d 辆\n", cars.size());
}
private boolean exists(List<Car> list, Car car) {
for (Car c : list) {
if (c.getId().equals(car.getId())) {
return true;
}
}
return false;
}
}
Main类
public class Main {
public static void main(String[] args) {
Saler saler = new Saler();
saler.addCar(new Car("凯越", "001"));
saler.addCar(new Car("君威", "002"));
saler.printStockInfo(2, 0);
saler.printSalesInfo();
}
}
关键概念解析
继承
在上述代码中,我们没有使用继承,但如果我们需要为“凯越”和“君威”添加更多属性或方法,我们可以创建一个基类CarType
,然后让“凯越”和“君威”继承自该基类。
封装
在Car
类中,我们将type
和id
属性设置为私有,并通过公共方法访问它们。这是封装的一个例子,它有助于保护数据不被外部代码直接访问。
多态
在这个案例中,我们没有使用多态,但如果我们需要对不同的车型执行不同的操作,我们可以使用接口或抽象类来实现多态。
总结
通过这个案例,我们深入了解了Java编程中的关键概念。在实际开发中,理解并应用这些概念将有助于我们编写更高效、更安全的代码。