public class TestingClass {
public static void main(String[] args) {
int numberRooms = 6;
double totalSpace;
Room[] rooms = new Room[numberRooms];
rooms[0] = new Room(20, 20);
rooms[1] = new Room(20, 20);
rooms[2] = new Room(22, 20);
rooms[3] = new Room(20, 20);
rooms[4] = new Room(25, 20);
rooms[5] = new Room(15, 13);
Garage garage = new Garage(20, "Cement", 1, 20, 1, 4);
for (int i = 0; i < numberRooms; i++) {
totalSpace = totalSpace + calculateRoomSpace(rooms[i]);
}
System.out.println("Total room space is " + totalSpace);
foo(garage);
}
public static double calculateRoomSpace(Room roomSpace) {
double newRoomSpace = roomSpace.calcFloorSpace();
return newRoomSpace;
}
public static void foo(Building myBuilding) {
System.out.println("Total floor space is " + myBuilding.calcFloorSpace());
}
}
我输入此代码并获取错误
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot instantiate the type Garage
at TestingClass.main(TestingClass.java:17)"
这里究竟出现了什么问题?
修改的 **这是车库类**
abstract public class Garage extends Building {
private int cars;
private String floorType;
private int garageLength;
private int garageWidth;
public Garage(int floors, int windows, int cars, String floorType,
int garageLength, int garageWidth) {
super(floors, windows);
this.cars = cars;
this.floorType = floorType;
this.garageLength = garageLength;
this.garageWidth = garageWidth;
}
@Override
public double calcFloorSpace() {
int floorSize;
floorSize = garageLength * garageWidth;
return floorSize;
}
public int getCars() {
return cars;
}
public void setCars(int cars) {
this.cars = cars;
}
public String getFloorType() {
return floorType;
}
public void setFloorType(String floorType) {
this.floorType = floorType;
}
public int getGarageLength() {
return garageLength;
}
public void setGarageLength(int garageLength) {
this.garageLength = garageLength;
}
public int getGarageWidth() {
return garageWidth;
}
public void setGarageWidth(int garageWidth) {
this.garageWidth = garageWidth;
}
@Override
public String toString() {
return "Garage [cars=" + cars + ", floorType=" + floorType
+ ", garageLength=" + garageLength + ", garageWidth="
+ garageWidth + "]";
}
}
希望这会有所帮助。不是这方面的专家,花了很长时间搞清楚这一点。谢谢
答案 0 :(得分:2)
您无法实例化抽象类。
你有两个选择:
abstract
,或Garage
的类,可以实例化。答案 1 :(得分:2)
您的Garage类被声明为抽象类无法实例化。请查看此更多详细信息Can an abstract class have a constructor?
答案 2 :(得分:1)
您无法实例化abstract
类的实例。您需要使您的类具体化(删除类上的abstract
修饰符并为所有方法提供实现),或者扩展抽象类以创建非抽象类。
当你删除abstract
修饰符时,编译器会告诉你缺少哪些抽象方法(如果有的话)。
答案 3 :(得分:0)
Garage是一个抽象类,因此无法实例化。只能实例化它的子类。