kotlin实现继承_Kotlin程序| 继承的例子
kotlin實現繼承
遺產 (Inheritance)
Inheritance is a mechanism wherein a new class is derived from an existing class.
繼承是一種機制,其中新類是從現有類派生的。
All Kotlin Classes have a common Superclass 'Any', it is the Default Superclass with no Super Type declared.
所有Kotlin類都有一個通用的超類“ Any”,它是沒有聲明任何超類型的默認超類。
class Student // implicitly inherits from Any'Any' Class has three methods
“任何”課程有三種方法
- equals()
- hashCode()
- toString()
By Default All class is Final in Kotlin, They can't be inherited.
默認情況下,所有類在Kotlin中都是Final,不能繼承。
Use 'open' keyword, to make class inheritable,
使用“ open”關鍵字,使類可繼承,
open class <class name> // make class inheritableTo declare explicit supertype, placer base class name after colon into the class header.
要聲明顯式超類,在冒號之后將放置器基類名稱放入類標題中。
open class Base{} class Derived : Base{}
Kotlin繼承計劃 (Program for Inheritance in Kotlin)
package com.includehelp//Declare class, use 'open' keyword //to make class inheritable //Class without declare primary constructor open class Company{//member functionfun getCompany(){println("Base Methods : Company Info")} } //Declare class using inheritance class Department : Company() {//member functionfun getDept(){println("Derived Method : Dept Info")} }//Declare class, use 'open' keyword //to make class inheritable open class Shape(val a:Int){fun getBaseValue(){println("Base value : $a")} } //if derived class has primary constructor //then base class can initialized there //using primary constructor parameters class Circle(val b:Int): Shape(b) {fun getChildValue(){println("Child value : $b")} }//Main Function, Entry point of program fun main(args:Array<String>){//create derived class objectval company = Department()//access base class functioncompany.getCompany()//access derived class functioncompany.getDept()//create derived class object and passed parameterval shape = Circle(20)//access base class functionshape.getBaseValue()//access derived class functionshape.getChildValue() }Output:
輸出:
Base Methods : Company Info Derived Method : Dept Info Base value : 20 Child value : 20翻譯自: https://www.includehelp.com/kotlin/example-of-inheritance.aspx
kotlin實現繼承
總結
以上是生活随笔為你收集整理的kotlin实现继承_Kotlin程序| 继承的例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: kodi播放时音频 杜比反复点亮
- 下一篇: c 僵尸进程_演示僵尸进程的C程序