Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Kotlin 继承


Kotlin 继承(子类和父类)

在 Kotlin 中,可以从一个类继承另一个类的属性和函数。我们将“继承概念”分为两类

  • 子类(子) - 从另一个类继承的类
  • 父类(父) - 被继承的类

在下面的例子中,MyChildClass(子类)继承了 MyParentClass 类(父类)的属性

示例

// Superclass
open class MyParentClass { val x = 5 } // Subclass class MyChildClass: MyParentClass() { fun myFunction() { println(x) // x is now inherited from the superclass } } // Create an object of MyChildClass and call myFunction fun main() { val myObj = MyChildClass() myObj.myFunction() }
自己尝试 »

示例说明

父类/父类前面使用 open 关键字,使其成为其他类应该继承属性和函数的类。

要从一个类继承,请指定子类的名称,后跟冒号 :,然后是父类的名称。

为什么以及何时使用“继承”?

- 它对于代码重用很有用:在创建新类时重用现有类的属性和函数。



×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.