kotlin 类和对象_Kotlin程序| 类和对象的示例(带有学生数据)

kotlin 类和对象

In the below program, we are creating a student class to input and print the student data like name, age. It is a simple example of creating class in Kotlin.

在下面的程序中,我们将创建一个学生班级,以输入和打印学生数据,例如姓名,年龄。 这是在Kotlin中创建类的简单示例。

Note:

注意:

  • The compiler creates a default constructor if we do not declare a constructor.

    如果我们不声明构造函数,则编译器将创建默认构造函数。

  • Class properties must be initialized.

    类属性必须初始化。

Kotlin学生课程 (Program for student class in Kotlin)

package com.includehelp

// Class declaration,
class Student{
    //member variables of class
    private var name: String=""
    private var age: Int=0

    //Member functions of class to set student name
    fun setStudentName(name:String){
        this.name=name
    }

    //Member functions of class to set student age
    fun setStudentAge(age:Int){
        this.age=age
    }

    //Member functions of class to return student details
    fun getStudentDetails():String{
        return "Name :  $name, Age : $age"
    }
}

//Main function, Entry Point of Program
fun main(args:Array<String>){
    //Create Object of Student Class
    val student1 = Student() // There is no 'new' keyword

    // set Student age and name to call member functions of class
    student1.setStudentName("Mike")
    student1.setStudentAge(30)

    //print Student details bt ccall getStudentDetails members functions
    println("Student : ${student1.getStudentDetails()}")

    //Create Second object of student class
    val student2 = Student()
    student2.setStudentName("Irina")
    student2.setStudentAge(23)
    println("Student : ${student2.getStudentDetails()}")
}

Output:

输出:

Student : Name :  Mike, Age : 30
Student : Name :  Irina, Age : 23


翻译自: https://www.includehelp.com/kotlin/example-of-class-and-object-with-student-data.aspx

kotlin 类和对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值