综合练习题自定义汽车类字段有汽车品牌、汽车价钱、汽车的颜色方法有跑、停要求封装当前类创建三个对象分别通过构造器初始化以及set方法初始化并打印汽车信息字段和方法
下面是一个符合要求的自定义汽车类的示例代码:
public class Car {
private String brand;
private double price;
private String color;
public Car(String brand, double price, String color) {
this.brand = brand;
this.price = price;
this.color = color;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public void run() {
System.out.println("The car is running.");
}
public void stop() {
System.out.println("The car has stopped.");
}
public static void main(String[] args) {
Car car1 = new Car("Toyota", 20000.0, "Red");
Car car2 = new Car("Honda", 25000.0, "Blue");
Car car3 = new Car();
car3.setBrand("BMW");
car3.setPrice(50000.0);
car3.setColor("Black");
System.out.println("Car 1:");
System.out.println("Brand: " + car1.getBrand());
System.out.println("Price: " + car1.getPrice());
System.out.println("Color: " + car1.getColor());
car1.run();
car1.stop();
System.out.println("\nCar 2:");
System.out.println("Brand: " + car2.getBrand());
System.out.println("Price: " + car2.getPrice());
System.out.println("Color: " + car2.getColor());
car2.run();
car2.stop();
System.out.println("\nCar 3:");
System.out.println("Brand: " + car3.getBrand());
System.out.println("Price: " + car3.getPrice());
System.out.println("Color: " + car3.getColor());
car3.run();
car3.stop();
}
}
上述代码定义了一个名为Car的汽车类,包含私有字段brand、price和color,以及公有的getter和setter方法用于访问和修改这些字段的值。此外,还定义了run()和stop()方法,用于模拟汽车的行驶和停止操作。
在main()方法中,创建了三个Car对象,并通过构造器和setter方法初始化这些对象的字段。最后,使用System.out.println()打印了每个汽车对象的信息(品牌、价格、颜色),并调用了run()和stop()方法模拟汽车的行驶和停止操作
原文地址: https://www.cveoy.top/t/topic/h3oQ 著作权归作者所有。请勿转载和采集!