Classes are closed by default, and to make a class open for inheritance, you must use the open keyword
open class Product(val name: String) {fun description() = "product:$name" // Open fun load() = "nothing.." } class ChildProduct: product ("child") {override fun load(): String = "" fun special() = "child special fun" }Copy the code
Without specifying it in code, each class inherits a common superclass called Any
Public open class Any {public open operator fun equals(other: Any?) : Boolean public open fun hashCode(): Int public open fun toString(): String }Copy the code
The object keyword
You can define a class that produces only one instance – singletons use the object keyword in three ways
- 1. Object declaration
- 2. Object expressions
- Companion objects: If you want to tie the initialization of an object to an instance, you can use companion objects. You can declare a companion object in a class definition using the Companion modifier. You can only have one companion object in a class
Println ("ApplicationConfig loading..") ) } fun doSomething()= print("doSomething.." )} fun main () {/ / the name of the class, the instance name ApplicationConfig. DoSomething () / / the same object print (ApplicationConfig) print (ApplicationConfig)}Copy the code
open class Player { open fun load() = "load..." } playlist () {playlist () {playlist () = playlist () {playlist () = playlist (); } print(p.load()) }Copy the code
Companion Object {private const val PATH = "XXX" fun Load () = File(PATH).readbytes ()}} fun main() {// Call (similar to Java static keyword) configmap.load ()}Copy the code
Nested classes
- If a class is only useful to another class, then it is logical to embed it in that class and keep the two classes together, using nested classes
Class Test1 {// InnerTest1(var name: String) {fun show() = "$name"} fun battle() {}} // Call test1.innertest1 ("name").show()Copy the code
Data classes
- Is a class dedicated to storing data
- Provides a personalized implementation of toString
- By default, compare objects compare their reference values, and data types provide personalized implementations of equals and hashCode
data class TestData(var x: Int, var y: Int) { var isRight = x > 0 && y > 0 } val testData1 = TestData(10, 10) val testData2 = TestData(10, Print (testData1 == testData2) print(testData2)Copy the code