欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

kotlin实现继承_Kotlin程序| 继承的例子

发布时间:2023/12/1 45 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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 inheritable
  • To 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程序| 继承的例子的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。