官术网_书友最值得收藏!

There's more...

It's important to keep in mind that, although we can define a default function implementation in the interface, we are not able to instantiate default values for interface properties. Unlike the class properties, properties of an interface are abstract. They don't have backing fields that could hold a current value (state). If we declare a property inside an interface, we need to implement it in the class or object that implements this interface. This is the main difference between interfaces and abstract classes. Abstract classes can have constructors and can store properties along with their implementations.

As with Java, we can't extend multiple classes; however, we can implement multiple interfaces. When we have a class implementing multiple interfaces containing default implementations, we are at risk of dealing with conflicts caused by functions having the same signatures:

interface A {
fun foo() {
// some operations
}
}

interface B {
fun foo() {
// other operations
}
}

In this case, we need to override the foo() function explicitly to resolve the conflict:

class MyClass: A, B {
override fun foo() {
print("I'm the first one here!")
}
}

Otherwise, we would get the following error:

Class 'MyClass' must override public open fun foo(): Unit because it inherits multiple interface methods of it.

主站蜘蛛池模板: 牙克石市| 临高县| 洛宁县| 固阳县| 莫力| 阜城县| 新沂市| 上虞市| 和静县| 昌邑市| 左贡县| 星座| 瓮安县| 黄浦区| 大渡口区| 肥西县| 安多县| 库尔勒市| 金堂县| 惠州市| 金湖县| 汉源县| 拜城县| 延吉市| 精河县| 馆陶县| 南华县| 平舆县| 宜州市| 安吉县| 巴林左旗| 宜章县| 吉林市| 宿松县| 台江县| 康保县| 隆林| 南雄市| 长泰县| 青铜峡市| 邹平县|