Class 'Room' is abstract; cannot be instantiated

瘦欲@ 提交于 2019-12-08 15:07:37

问题


I have a class an abstract class Room which has subclasses Family and Standard, I have created room = new ArrayList<Room>(); within a Hostel class. I have a method to add a room to the ArrayList;

public String addRoom(String roomNumber, boolean ensuite)
{
    if  (roomNumber.equals("")) 
        return "Error - Empty name field\n";
    else

    room.add( new Room(roomNumber,ensuite) );
    return  "RoomNumber: " + roomNumber + " Ensuite: " + ensuite 
     + "  Has been added to Hostel " + hostelName;
}

However I get the compile time error;

Room is abstract; cannot be instantiated

I understand that abstract classes cannot be instantiated, but what is the best way to add rooms?


回答1:


You have this error because you are trying to create an instance of abstract class, which is impossible. You have to

room.add(new Family(roomNumber, ensuoute));

or

room.add(new Standard(roomNumber, ensuoute));



回答2:


The error says it all: Room is an abstract class, and abstract classes cannot be instantiated.

You're trying to instantiate Room here:

new Room(roomNumber,ensuite)

You can only create instances of concrete (i.e. non-abstract) classes. It is likely to be the case that Family and Standard are concrete classes and can therefore be instantiated.

To fix this, you'll need to figure out the correct room type given the room number, and instantiate the appropriate class.




回答3:


You are creating an instance of an abstract class;

room.add(new Room(roomNumber,ensuite));

This is not correct.



来源:https://stackoverflow.com/questions/8519943/class-room-is-abstract-cannot-be-instantiated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!