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 中的一切都与类和对象相关,以及它们的属性和函数。例如:在现实生活中,汽车是一个对象。汽车具有属性,例如品牌、重量和颜色,以及函数,例如驾驶和刹车。

类就像一个对象构造器,或者创建对象的“蓝图”。


创建类

要创建类,请使用class关键字,并指定类的名称。

示例

创建一个Car类以及一些属性(品牌、型号和年份)。

class Car {
  var brand = ""
  var model = ""
  var year = 0
} 

属性基本上是属于类的变量

需要了解:建议使用大写字母开头类名,以提高组织性。


创建对象

现在我们可以使用名为Car的类来创建对象。

在下面的示例中,我们创建了一个名为c1Car对象,然后我们使用点语法(.)访问c1的属性,就像我们访问数组和字符串属性一样。

示例

// Create a c1 object of the Car class
val c1 = Car()

// Access the properties and add some values to it
c1.brand = "Ford"
c1.model = "Mustang"
c1.year = 1969

println(c1.brand)   // Outputs Ford
println(c1.model)   // Outputs Mustang
println(c1.year)    // Outputs 1969 
自己试试 »


多个对象

您可以为一个类创建多个对象。

示例

val c1 = Car()
c1.brand = "Ford"
c1.model = "Mustang"
c1.year = 1969

val c2 = Car()
c2.brand = "BMW"
c2.model = "X5"
c2.year = 1999

println(c1.brand)  // Ford
println(c2.brand)  // BMW
自己试试 »


×

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.