用Java创建一个 汽车类(价格、品牌、颜色、尺寸 ;驾驶.... 播放音乐....) 属性为私有属性,方法为公关共,午参、有参构造方法 实现两个具体的对象(大众、宝马)
时间: 2023-07-10 12:15:38 浏览: 37
好的,我可以帮你完成这个Java题目。以下是实现:
```
public class Car {
private double price;
private String brand;
private String color;
private String size;
public Car() {
}
public Car(double price, String brand, String color, String size) {
this.price = price;
this.brand = brand;
this.color = color;
this.size = size;
}
public void drive() {
System.out.println("正在驾驶" + brand + "汽车");
}
public void playMusic() {
System.out.println("正在播放音乐");
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
}
```
然后我们可以创建两个具体的对象,如下所示:
```
public class Main {
public static void main(String[] args) {
Car volkswagen = new Car(150000, "大众", "白色", "中型");
Car bmw = new Car(300000, "宝马", "黑色", "大型");
volkswagen.drive();
volkswagen.playMusic();
System.out.println("大众汽车的价格:" + volkswagen.getPrice());
bmw.drive();
bmw.playMusic();
System.out.println("宝马汽车的价格:" + bmw.getPrice());
}
}
```
输出结果为:
```
正在驾驶大众汽车
正在播放音乐
大众汽车的价格:150000.0
正在驾驶宝马汽车
正在播放音乐
宝马汽车的价格:300000.0
```
希望这个示例程序对你有所帮助!