20

I have an abstract class Room which has subclasses Family and Standard.

I have created room = new ArrayList<Room>(); within a Hostel class and 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 following 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 a room?

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
Darren Burgess
  • 4,200
  • 6
  • 27
  • 43
  • 3
    You say you "have an abstract class `Room`", and you're asking why the compiler complains when you try to instantiate it? – Oliver Charlesworth Dec 15 '11 at 12:14
  • 1
    I think you should have a quick glance at this page: http://docs.oracle.com/javase/tutorial/ :-) – Lukas Eder Dec 15 '11 at 12:14
  • Why did you you made room abstract? Ask yourself if you really understand what `abstract` does and you should be able to answer the question yourself. – kapex Dec 15 '11 at 12:15
  • where you are giving this method declaration? – alishaik786 Dec 15 '11 at 12:15
  • 1
    You cannot create instance of `abstract` class, the concrete class is needed. For example: `room.add( new BigRoom(roomNumber,ensuite) );` – Alex K Dec 15 '11 at 12:15

3 Answers3

15

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));
Valchev
  • 1,490
  • 14
  • 17
7

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
-1

You are creating an instance of an abstract class;

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

This is not correct.

alishaik786
  • 3,696
  • 2
  • 17
  • 25