【发布时间】:2019-07-19 05:50:20
【问题描述】:
当前代码单独打印语句,而我想将有关汽车的所有变量(颜色、气缸数和座位数)串在一起,并将有关卡车的所有变量(颜色、气缸数、和牵引能力)。可变座椅在子类Car 中并打印它自己的独立语句,而可变牵引能力在子类Truck 中也打印它自己的语句。我想用一句话描述汽车的所有变量,用一句话描述卡车的所有变量。
import java.util.Scanner;
class Vehicle {
Scanner s = new Scanner(System.in);
private String color;
private int noOfCylinders;
public int noOfSeats;
public int towingCapacity;
public Vehicle() {
color = "Black";
noOfCylinders = 0;
noOfSeats = 1;
towingCapacity =0;
}
public Vehicle(String color, int noOfCylinders, int noOfSeats, int towingCapacity) {
this.color = color;
this.noOfCylinders = noOfCylinders;
this.noOfSeats = noOfSeats;
this.towingCapacity = towingCapacity;
}
public void setColor() {
System.out.print("Enter color of vehicle: ");
color = s.nextLine();
}
public String getColor() {
return color;
}
public void setNoOfCylinders() {
System.out.print("Enter number of cylinders: ");
noOfCylinders = s.nextInt();
}
public int getNoOfCylinders() {
return noOfCylinders;
}
public void setNoOfSeats() {
System.out.print("Enter numer of seats: ");
noOfSeats = s.nextInt();
}
public void setTowingCapacity() {
System.out.print("Enter towing Capacity: ");
towingCapacity = s.nextInt();
}
public String toString() {
String information;
information = "is " + color + " and it has " + noOfCylinders + " cylinders.";
return information;
}
}
public class CreateVehicle {
public static void main(String[] args) {
Car CarObject = new Car();
Truck TruckObject = new Truck();
CarObject.getColor();
CarObject.setColor();
CarObject.getNoOfCylinders();
CarObject.setNoOfCylinders();
CarObject.toString();
CarObject.setNoOfSeats();
TruckObject.getColor();
TruckObject.setColor();
TruckObject.getNoOfCylinders();
TruckObject.setNoOfCylinders();
TruckObject.toString();
TruckObject.setTowingCapacity();
CarObject.toStringSeats();
TruckObject.toStringCapacity();
System.out.print(("\nThe car ")+CarObject.toString());
System.out.print(("\nThe truck ")+TruckObject.toString());
}
}
class Car extends Vehicle{
public void toStringSeats(){
System.out.print("\nThe car has " + noOfSeats + " seats.");
}
}
class Truck extends Vehicle {
public void toStringCapacity() {
System.out.print("\nThe truck has a towing capacity of " + towingCapacity + ".");
}
}
【问题讨论】:
标签: java string inheritance overriding superclass