128

In Java, you can do such thing as:

class MyClass extends SuperClass implements MyInterface, ...

Is it possible to do the same thing in Kotlin? Assuming SuperClass is abstract and does not implement MyInterface

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
chntgomez
  • 2,058
  • 3
  • 19
  • 31

2 Answers2

213

There's no syntactic difference between interface implementation and class inheritance. Simply list all types comma-separated after a colon : as shown here:

abstract class MySuperClass
interface MyInterface

class MyClass : MySuperClass(), MyInterface, Serializable

Multiple class inheritance is prohibited while multiple interfaces may be implemented by a single class.

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
  • 4
    So does order matter, or does the parenthesis take care of which is the parent and which are the interfaces? – SMBiggs Jan 13 '20 at 23:10
  • I can't think of a reason why order would matter. Yes, every abstract class will need parens while interfaces work without. The compiler knows whether you're implementing an interface or extending a super class – s1m0nw1 Jan 16 '20 at 09:12
10

This is the general syntax to use when a class is extending (another class) or implementing (one or serveral interfaces):

class Child: InterfaceA, InterfaceB, Parent(), InterfaceZ

Note that the order of classes and interfaces does not matter.

Also, notice that for the class which is extended we use parentheses, thee parenthesis refers to the main constructor of the parent class. Therefore, if the main constructor of the parent class takes an argument, then the child class should also pass that argument.

interface InterfaceX {
   fun test(): String
}

open class Parent(val name:String) {
    //...
}

class Child(val toyName:String) : InterfaceX, Parent("dummyName"){

    override fun test(): String {
        TODO("Not yet implemented")
    }
}
Mr.Q
  • 4,316
  • 3
  • 43
  • 40