Kotlin 简明教程
Kotlin - Class and Objects
Kotlin同时支持函数式和面向对象编程。在讨论Kotlin的函数式特性时,我们有诸如函数、高阶函数和lambda之类的概念,它们将Kotlin表示为一种函数式语言。
Kotlin supports both functional and object-oriented programming. While talking about functional features of Kotlin then we have concepts like functions, higher-order functions and lambdas etc. which represent Kotlin as a functional language.
Kotlin 也支持面向对象编程 (OOP) 并提供诸如抽象、封装、继承等功能。本教程将通过简单的步骤教你所有 Kotlin OOP 功能。
Kotlin also supports Object Oriented Programming (OOP) and provides features such as abstraction, encapsulation, inheritance, etc. This tutorial will teach you all the Kotlin OOP features in simple steps.
Kotlin Classes
类是对对象的蓝图,它定义一个模板,用于创建所需的类。
A class is a blueprint for the objects which defines a template to be used to create the required objects.
类是任何面向对象编程语言的主要构建块。使用 class 关键字定义 Kotlin 类。以下是创建 Kotlin 类的语法:
Classes are the main building blocks of any Object Oriented Programming language. A Kotlin class is defined using the class keyword. Following is the syntax to create a Kotlin Class:
class ClassName { // Class Header
//
// Variables or data members
// Member functions or Methods
//
...
...
}
默认情况下,Kotlin 类为 public ,我们可以使用将在 Visibility Modifiers 中学习的不同修饰符控制类成员的可见性。
By default, Kotlin classes are public and we can control the visibility of the class members using different modifiers that we will learn in Visibility Modifiers.
Kotlin Objects
对象是从 Kotlin 类创建的,它们共享由类的形式定义的公共属性和行为数据成员(属性)和成员函数(行为)。
The objects are created from the Kotlin class and they share the common properties and behaviours defined by a class in form of data members (properties) and member functions (behaviours) respectively.
声明类对象的语法为:
The syntax to declare an object of a class is:
var varName = ClassName()
我们可以使用 . (点)运算符访问类的属性和方法,如下所示:
We can access the properties and methods of a class using the . (dot) operator as shown below:
var varName = ClassName()
varName.property = <Value>
varName.functionName()
Example
下面是一个示例,我们将创建一个 Kotlin 类及其对象,通过该对象我们将访问该类不同的数据成员。
Following is an example where we will create one Kotlin class and its object through which we will access different data members of that class.
class myClass {
// Property (data member)
private var name: String = "Tutorialspoint.com"
// Member function
fun printMe() {
print("The best Learning website - " + name)
}
}
fun main(args: Array<String>) {
val obj = myClass() // Create object obj of myClass class
obj.printMe() // Call a member function using object
}
上面的代码段将在浏览器中生成以下输出,其中我们将使用自己对象 obj 调用 myClass 的 printMe() 方法。
The above piece of code will yield the following output in the browser, where we are calling printMe() method of myClass with the help of its own object obj.
The best Learning website - Tutorialspoint.com
Kotlin Nested Class
根据定义,如果在一个类中创建了另一个类,则称为 nested class 。
By definition, when a class has been created inside another class, then it is called as a nested class.
Kotlin 嵌套类默认是静态的,因此无需创建该类的任何对象就可以通过 . 点运算符访问它。同时,我们无法在嵌套类中访问外部类成员。
Kotlin nested class is by default static, hence, it can be accessed without creating any object of that class but with the help of . dot operator. Same time we cannot access members of the outer class inside a nested class.
以下是创建嵌套类的简单语法:
Following is the simple syntax to create a nested class:
class OuterClass{
// Members of Outer Class
class NestedClass{
// Members of Nested Class
}
}
现在我们可以如下创建嵌套类的对象:
Now we can create an object of nested class as below:
val object = OuterClass.NestedClass()
Example
以下是展示 Kotlin 如何解释嵌套类的示例。
Following is the example to show how Kotlin interprets a nested class.
fun main(args: Array<String>) {
val obj = Outer.Nested()
print(obj.foo())
}
class Outer {
class Nested {
fun foo() = "Welcome to The TutorialsPoint.com"
}
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
Welcome to The TutorialsPoint.com
Kotlin Inner Class
当使用关键词 inner 标记嵌套类时,它将被称为 Inner class 。内部类可以通过外部类的数据成员访问。
When a nested class is marked with a keyword inner, then it will be called as an Inner class. An inner class can be accessed by the data member of the outer class.
与嵌套类不同,内部类可以访问外部类成员。我们无法直接创建内部类对象,但可以使用外部类对象创建它。
Unlike a nested class, inner class can access members of the outer class. We cannot directly create an object of the inner class but it can be created using the outer class object.
以下是创建内部类的简单语法:
Following is the simple syntax to create an inner class:
class OuterClass{
// Members of Outer Class
class inner InnerClass{
// Members of Inner Class
}
}
现在我们可以如下创建内部类的对象:
Now we can create an object of inner class as below:
val outerObj = OuterClass()
val innerObj = outerObj.InnerClass()
Example
以下是展示 Kotlin 如何解释内部类的示例。
Following is the example to show how Kotlin interprets an inner class.
fun main(args: Array<String>) {
val obj = Outer().Inner()
print(obj.foo())
}
class Outer {
private val welcomeMessage: String = "Welcome to the TutorialsPoint.com"
inner class Inner {
fun foo() = welcomeMessage
}
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
Welcome to The TutorialsPoint.com
Anonymous Inner Class
匿名内部类是一个非常好的概念,可以让程序员的生活变得非常轻松。每当我们实现一个接口时,匿名内部块的概念就会出现在图片中。使用运行时对象引用创建接口对象的概念称为匿名类。
Anonymous inner class is a pretty good concept that makes the life of a programmer very easy. Whenever we are implementing an interface, the concept of anonymous inner block comes into picture. The concept of creating an object of interface using runtime object reference is known as anonymous class.
Example
以下是一个示例,展示了我们将如何创建接口,以及如何使用匿名内部类机制创建该接口的对象。
Following is the example to show how we will create an interface and how we will create an object of that interface using Anonymous Inner class mechanism.
fun main(args: Array<String>) {
var programmer :Human = object:Human { // Anonymous class
override fun think() { // overriding the think method
print("I am an example of Anonymous Inner Class ")
}
}
programmer.think()
}
interface Human {
fun think()
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
I am an example of Anonymous Inner Class
Kotlin Type Aliases
Kotlin 类型别名是指为现有类型提供替代名称的一种方式。类型别名提供了一个更干净的方式来编写更可读的代码。
Kotlin Type Aliases means a way to give an alternative name to an existing type. Type alias provides a cleaner way to write a more readable code.
考虑以下一个返回用户信息、姓氏和年龄的函数:
Consider a following function which returns a user info first name, last name and age:
fun userInfo():Triple<String, String, Int>{
return Triple("Zara","Ali",21)
}
现在,我们可以按照 Triple 给定的类型别名如下:
Now we can a type alias for the given Triple as follows:
typealias User = Triple<String, String, Int>
最后,上面的函数可以写成如下所示,它看起来比上面的代码更简洁:
Finally the above function can be written as below, which looks more clean than above code:
fun userInfo():User{
return Triple("Zara","Ali",21)
}
Example
以下是展示 Kotlin 中类型别名的用法的一个完整示例代码:
Following is the complete working example to show the usage of type alias in Kotlin:
typealias User = Triple<String, String, Int>
fun main() {
val obj = userInfo()
print(obj)
}
fun userInfo():User{
return Triple("Zara","Ali",21)
}
当你运行上述 Kotlin 程序时,它将生成以下输出:
When you run the above Kotlin program, it will generate the following output:
(Zara, Ali, 21)