Detailed Explanation of the Difference between Kotlin Anonymous Class Implementation Interface and Abstract Class

  • 2021-11-24 02:49:01
  • OfStack

I will not talk too much nonsense, or on the code

Interface:


interface OnBind {

 fun onBindChildViewData(holder: String, itemData: Any, position: Int)

}

 lesson.does(object : OnBind {
  override fun onBindChildViewData(holder: String, itemData: Any, position: Int) {
   println(holder + itemData + position)
  }
 })

Abstract class:


abstract class AbstractOnBind {

 abstract fun onBindChildViewData(holder: String, itemData: Any, position: Int)

}

 lesson.does(object : AbstractOnBind() {
  override fun onBindChildViewData(holder: String, itemData: Any, position: Int) {
   println(holder + itemData + position)
  }
 })

See the difference? Haha, it doesn't matter if you can't see it, I tell you.

The only difference between them is the following sentence when calling, and the abstract class has one more parenthesis.

object : OnBind
object : AbstractOnBind()

There are only one difference, in fact, it is totally different in essence.

When implementing the interface, object replaces one object of new in java, where ":" is followed by the interface, and there is no construction method for the interface, which means that object implements this interface;

When implementing an abstract class, there is () after the abstract method, which can be understood as calling the construction method of the abstract method. After "new" gives an object, it is assigned to object.

Summary 1: In order to understand, you can think like this (the actual principle may not be the case). When interfacing, you should first have object, and then let object realize the interface; When abstracting a class, the abstract method in the abstract class is implemented first, and then an object is constructed by the construction method, and then it is given to object


Related articles: