Reprinted from: https://www.cnblogs.com/jaymo/articles/6924144.html
Create an instance of the class
To create an instance of a class, we call the constructor just like a normal function:
1
2
3
|
val invoice = Invoice()
val customer = Customer(
"Joe Smith"
)
|
Note that Kotlin does not have the new keyword.
inherit
In Kotlin all classes have a common superclass Any
, which is the default superclass for classes without a supertype declaration
1
|
class Example
//
从 Any 隐式继承
|
Any
No java.lang.Object
; in particular, it has no members except equals()
, hashCode()
and .toString()
To declare an explicit supertype, we put the type after the colon in the class header:
1
2
3
|
open
class Base(p: Int)
class Derived(p: Int) : Base(p)
|
The open annotation on a class is the opposite of final in Java, it allows other classes to inherit from this class. By default, all classes in Kotlin are final, which corresponds to Item 17 of the Effective Java book: Either design for inheritance and document it, or disallow inheritance.
Override method
We mentioned earlier that Kotlin strives for clarity. Unlike Java, Kotlin needs to explicitly annotate overridable members (which we call open ) and overridden members:
1
2
3
4
5
6
7
|
open
class Base {
open
fun
v
() {}
fun nv() {}
}
class Derived() : Base() {
override fun
v
() {}
}
|
A member marked override is itself open, that is, it can be overridden in subclasses. If you want to prevent overriding again, use the final keyword:
1
2
3
|
open
class AnotherDerived() : Base() {
final override fun
v
() {}
}
|
Override property
Property overriding is similar to method overriding; properties declared in a superclass and then redeclared in a derived class must begin with override, and they must have compatible types. Each declared property can be overridden by a property with an initializer or by a property with a getter method.
1
2
3
4
5
6
7
|
open
class Foo {
open
val x: Int get { …… }
}
class Bar1 : Foo() {
override val x: Int = ……
}
|
You can also var
override a property with a val
property, but not the other way around. This is allowed because a val
property essentially declares a getter method, and overriding it to var
just declare an additional setter method in the subclass.
companion object
Unlike Java or C#, classes do not have static methods in Kotlin. In most cases it recommends simply using package-level functions.
If you need to write a function (for example, a factory method) that can be called without an instance of the class, but needs to access the inside of the class (for example, a factory method), you can write it as a member of the object declaration inside the class.
More specifically, if you declare a companion object inside your class , you can call its members using the same syntax you would call a static method in Java/C#, using only the class name as a qualifier.