【发布时间】:2015-05-03 14:50:50
【问题描述】:
我正在为一个任务编写一个程序,该任务应该输出有关车辆的信息,其中 Vehicle 是超类,Car、Truck 和 Van 是子类。我们的导师给了我们主要的方法,所以我知道这个问题必须在我为子类编写的代码中。
我已根据建议的反馈更新了我的代码,并在第 3 行遇到了一个新错误:无法访问类型为 AssignmentEX2 的封闭实例。必须使用类型的封闭实例来限定分配 AssignmentEX2(例如 x.new A(),其中 x 是 AssignmentEX2 的一个实例)。
public class AssignmentEX2 {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle("5554EAWV3898");
System.out.println(vehicle.toString());
vehicle.rentVehicle();
System.out.println(vehicle.toString());
vehicle.returnVehicle();
System.out.println(vehicle.toString());
System.out.println();
Car car = new Car("6903NMME5853", 4);
System.out.println(car.toString());
car.rentVehicle();
System.out.println(car.toString());
System.out.println();
Truck truck = new Truck("7242OAHT0021", 26, 3);
System.out.println(truck.toString());
truck.rentVehicle();
System.out.println(truck.toString());
System.out.println();
Van van = new Van("5397NQRO4899", 11);
System.out.println(van.toString());
van.rentVehicle();
System.out.println(van.toString());
}
class Vehicle {
String vin;
Boolean rented = false;
public Vehicle(String vin) {
}
public String getVin() {
return vin;
}
public Boolean isRented() {
return rented;
}
public void rentVehicle() {
rented = true;
}
public void returnVehicle() {
rented = false;
}
public String toString() {
return("VIN: " + vin + "\nRented: " + rented );
}
}
class Car extends Vehicle {
int doors;
public Car (String vin, int doors) {
super( vin );
}
public int getDoors() {
return doors;
}
public String toString() {
return("VIN: " + vin + "\nRented: " + rented + "\nDoors: " + doors);
}
}
class Truck extends Vehicle {
int boxSize;
int axles;
public Truck(String vin, int boxSize, int axles) {
super( vin );
}
public int getBoxSize() {
return boxSize;
}
public int getAxles() {
return axles;
}
public String toString() {
return("VIN: " + vin + "\nRented: " + rented + "\nBox Size: " + boxSize + "\nAxles: "
+ axles);
}
}
class Van extends Vehicle {
int seats;
public Van (String vin, int seats) {
super( vin );
}
public int getSeats() {
return seats;
}
public String toString() {
return("VIN: " + vin + "\nRented: " + rented + "\nSeats: " + seats);
}
}
}
【问题讨论】:
-
如何这段代码不起作用?你得到什么错误?
-
第 3 行:无法访问类型为 AssignmentEX2 的封闭实例。必须使用 AssignmentEX2 类型的封闭实例来限定分配(例如 x.new A(),其中 x 是 AssignmentEX2 的实例)。
-
@KyleJosephGreen 现在参考我的答案
-
知道了。我关闭了公共课程并摆脱了错误。我现在有一些运行时错误,但没有编译错误。不过,我会对此进行一些研究,看看我是否无法弄清楚它们发生的原因。
标签: java object constructor polymorphism subclass