Search code examples
androidandroid-room

Why is it recommended to make the class that extends Room Database to abstract?


What is the reason behind it ? Is it for performance or compulsion? Please Explain


Solution

  • First, we need to understand one thing about Abstract Classes in that they allow you to skip implementing some default methods of the parent class.

    Unlike Interfaces where you implement all the interface methods, in Abstract Classes world the child classes can choose to implement what is specific to the child class and leave out the other implementations if not needed.

    If you do a deep dive on the parent RoomDatabase documentation you will note that it is the Base class for all Room databases and it has some methods not relavant to the child classes e.g. createOpenHelper(), createInvalidationTracker(), clearAllTables().

    In fact the docs clearly mention that 'RoomDatabase provides direct access to the underlying database implementation but you should prefer using Dao classes'.

    In simple terms, you should mark your RoomDatabase class as Abstract to enable your class become flexible and skip implementing unnecessary methods of the RoomDatabase Base Class.

    This is true because when you don't mark the class as Abstract, you will get an error and Android Studio will prompt you to implement the above Base Class methods.

    So in Kotlin you will do something like this:

    @Database(entities = [Note::class], version = 1)
    abstract class NoteDatabase :RoomDatabase() {
        
        //Property must be initialized or be abstrac
     abstract val noteDAO:NoteDAO
     
    }
    

    Here the NoteDatabase inherits from RoomDatabase to make it a RoomDatabase Object- it doesn't need parent's default implementations therefore it skips those because it is marked with Abstract.

    NoteDatabase only needs to declare the an abstract noteDao variable. This is so that NoteDatabase knows about DAO Interface and this variable is also used for testing.