Answer the question
In order to leave comments, you need to log in
How to access a class through an interface?
I do not quite understand how and why, I read that calling class methods through an interface makes it easier to make changes in the future. So I wrote such an example, and I don’t see where it simplifies.
interface IServer {
fun getData()
}
class Server:IServer {
override fun getData() {
println("... getting data")
}
}
class Client(val iServer: IServer) {
fun connect(){
println("connecting...")
iServer.getData()
}
}
fun main(){
val client = Client(Server())
client.connect()
}
Answer the question
In order to leave comments, you need to log in
Good afternoon!
In frameworks, for example, in the same Spring, such a principle as DI (dependency injection) is implemented. It all boils down to the fact that you can inject the interface instead of the implementation itself. This simplifies the testing and development process, since you can "slip" another implementation of this interface. For example, in production, you need to connect to a real database and use the appropriate repositories, and during testing, you can mock other implementations of the interface.
Let's say that you have an IServer interface with a connect() method.
And it may have different implementations. For example,
FtpConnect implements IServer, SshConnect implements IServer
Accordingly, by injecting the IServer dependency into the code, you can specify which implementation of this interface should be injected. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question