Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class 'Room' is abstract; cannot be instantiated

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?

like image 944
Darren Burgess Avatar asked Dec 15 '11 12:12

Darren Burgess


People also ask

Is abstract Cannot be instantiated?

Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .

Can an abstract class be instantiated?

Abstract classes have the following features: An abstract class cannot be instantiated. An abstract class may contain abstract methods and accessors.

What is the meaning of abstract class Cannot be instantiated?

Declaring a class as abstract means that it cannot be directly instantiated, which means that an object cannot be created from it.

Can interface Cannot be instantiated?

No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete. Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.


1 Answers

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));
like image 102
Valchev Avatar answered Oct 22 '22 04:10

Valchev