定义类 Vehlcles:属性包括 size、color、seats,还有一个带参数的构造方法和一个显 示信息的方法。然后从此类中派生 Car 类,其中子类也有构造方法和显示信息的方法。 编写测试类程序,创建父类的对象,再创建子类的对象,用它们的显示信息的方法输 出它们的信息。
时间: 2023-06-05 08:06:45 浏览: 174
好的,您的问题是关于类的继承和对象的创建。以下是您需要的代码:
```java
class Vehicles {
private String size;
private String color;
private int seats;
public Vehicles(String size, String color, int seats) {
this.size = size;
this.color = color;
this.seats = seats;
}
public void displayInfo() {
System.out.println("Size: " + size);
System.out.println("Color: " + color);
System.out.println("Seats: " + seats);
}
}
class Car extends Vehicles {
public Car(String size, String color, int seats) {
super(size, color, seats);
}
public void displayInfo() {
System.out.println("This is a car.");
super.displayInfo();
}
}
public class Test {
public static void main(String[] args) {
Vehicles v1 = new Vehicles("medium", "blue", 5);
Car c1 = new Car("small", "red", 2);
v1.displayInfo();
System.out.println();
c1.displayInfo();
}
}
```
您可以将上述代码粘贴到 Java IDE 中运行,结果将是:
```
Size: medium
Color: blue
Seats: 5
This is a car.
Size: small
Color: red
Seats: 2
```
阅读全文