实操: 请使用抽象类的思想实现案例,并在测试类中进行测试 (1)定义车类( Car) 成员变量:品牌( brand )、价格(price)、颜色(colour) 构造方法:无参、带参 成员方法:get/set方法、show( ) 抽象方法 function(); (2)定义跑车类(SportsCar) 构造方法:无参、带参 成员方法:重写function(){…},并输出一条语句“超级跑车” (3)货车类(van) 成员变量:车轮数(wheels) 构造方法:无参、带参 成员方法:get/set方法,重写function(){…},并输出一条语句“大型货车” (4)定义测试类(CarDemo),使用无参创建对象和有参创建对象写代码测试 java案例
时间: 2024-03-05 15:48:59 浏览: 69
抽象类及接口的实例及测试
5星 · 资源好评率100%
下面是使用抽象类的思想实现案例的代码:
Car.java
```
public abstract class Car {
private String brand;
private double price;
private String colour;
public Car() {
}
public Car(String brand, double price, String colour) {
this.brand = brand;
this.price = price;
this.colour = colour;
}
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 getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public void show() {
System.out.println("Brand: " + brand);
System.out.println("Price: " + price);
System.out.println("Colour: " + colour);
}
public abstract void function();
}
```
SportsCar.java
```
public class SportsCar extends Car {
public SportsCar() {
super();
}
public SportsCar(String brand, double price, String colour) {
super(brand, price, colour);
}
@Override
public void function() {
System.out.println("Super Sports Car");
}
}
```
Van.java
```
public class Van extends Car {
private int wheels;
public Van() {
super();
}
public Van(String brand, double price, String colour, int wheels) {
super(brand, price, colour);
this.wheels = wheels;
}
public int getWheels() {
return wheels;
}
public void setWheels(int wheels) {
this.wheels = wheels;
}
@Override
public void function() {
System.out.println("Large Van");
}
}
```
CarDemo.java
```
public class CarDemo {
public static void main(String[] args) {
Car car1 = new SportsCar("Ferrari", 3000000.0, "Red");
car1.show();
car1.function();
System.out.println("----------------------");
Car car2 = new Van("Benz", 800000.0, "White", 8);
car2.show();
car2.function();
}
}
```
输出结果:
```
Brand: Ferrari
Price: 3000000.0
Colour: Red
Super Sports Car
----------------------
Brand: Benz
Price: 800000.0
Colour: White
Large Van
```
阅读全文