1
votes

I want to understand what is happening behind the scenes in a RoomDatabase, that it requires the DAO to be either an interface or an abstract class. I've been searching for quite a while, but all articles and documentation only explain the how, not the why.

2
because the room compiler generates the source code implementing that interface - see build/generated/source folder - pskink
Most likely, you would have to ask a Google engineer for a clear confirmation. That's why questions of the form "why did Developer X make Decision Y?" are not great for Stack Overflow. - CommonsWare
Interface kinda makes sense to me because we don't provide any method bodies, but when I make the class abstract, I can still add method implementations. So I wonder why this pattern is enforced. I am still a beginner. - Florian Walther
Ok it just clicked for me. Interfaces and abstract classes are the only classes where I don't have to implement a method body - Florian Walther

2 Answers

1
votes

It is not just the Room, Retrofit and other libraries use this pattern too, it is called Programming to an Interface. Instead of just creating a concrete implementation you just specify the stuff you want to do and they provide you with an implementation that will behave as you requested.

For further study you can check this article: https://tuhrig.de/programming-to-an-interface/

0
votes

The data access object, or Dao, is an annotated class where you specify SQL queries and associate them with method calls.

The DAO must be an interface or abstract class because we want to make sure that the CRUD methods we will be creating inside it are implemented at the Class level. Which is actually the whole idea of having an interface or abstract class.