Home > Software engineering >  How to check whether parent class implements child class interface in Kotlin
How to check whether parent class implements child class interface in Kotlin

Time:10-03

I have 2 classes Student and Teacher and one interface ICanOperate. The child class Student implements the interface ICanOperate. How to check whether the super class Teacher implements the interface as well?

open class Teacher(
    var name: String,
    var registry: Int,
    internal var phoneNumber: String
){
    override fun toString(): String {
        return ("$name, $registry, $phoneNumber")
    }
}

class Student(name : String, registry : Int, phoneNumber : String , var badgeNumber : String) : ICanOperate , Teacher (name, registry , phoneNumber)  {
    override fun OperateClass(): String {
        return "Book please"
    }
    override fun toString(): String {
        return ("$name ($registry) - $phoneNumber Badge : $badgeNumber" );
    }
}

interface ICanOperate {
    fun OperateClass () : String;
}

fun main(args : Array<String>) {
    var obj = Student("Ash", 157, "9029897581", "B00894354")
    var obj3 = Teacher("Elon", 1232, "9029893188")
   
}

CodePudding user response:

How to check whether the super class Teacher implements the interface as well?

It doesn't. We know it from the code: Teacher doesn't implement the interface.

However, I think what you meant is "how to check whether some instance of Teacher happens to be of a class that does implement the interface?".

In that case, you can do it simply using an is check:

if (someTeacher is ICanOperate) {
    // do something
}
  • Related