Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend and implement at the same time in Kotlin

Tags:

java

kotlin

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

like image 638
chntgomez Avatar asked Jan 22 '18 22:01

chntgomez


People also ask

How do you implement and extend at the same time in Kotlin?

In this article, we will take an example to demonstrate how we can extend and implement in the same class. In this example, We will be creating an interface and a dummy Parent class. From the Child class, we will extend the Parent class and implement the interface.

Can we use extend and implement at the same time?

Yes, you can. But you need to declare extends before implements : public class DetailActivity extends AppCompatActivity implements Interface1, Interface2 { // ... } Any number of interfaces can be implemented, if more than one then each needs to be separated with a comma.

Can you extend a class and implement an interface at the same time?

Note: A class can extend a class and can implement any number of interfaces simultaneously.

Should implements or extends first?

The extends always precedes the implements keyword in any Java class declaration. When the Java compiler compiles a class into bytecode, it must first look to a parent class because the underlying implementation of classes is to point to the bytecode of the parent class - which holds the relevant methods and fields.


2 Answers

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.

like image 166
s1m0nw1 Avatar answered Oct 13 '22 19:10

s1m0nw1


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")
    }
}
like image 10
Mr.Q Avatar answered Oct 13 '22 20:10

Mr.Q