Kotlin Introduction (iv)--Class _kotlin

Source: Internet
Author: User
Reference

Official website class

Defines a class by using the Class keyword.

All classes in Kotlin inherit from any class, and the any class has only hashcode,tostring and equals three methods.

A class is composed of the class name, the class header, and the body of the class-the main body of the class, which is wrapped up in braces-three parts. Where class headers, class bodies are optional. If there is no class body, the curly braces can be omitted. Such as:

Class Demo//Definition of classes, no body of class, so even curly braces can be omitted
Instantiated with Java type, except to remove the new keyword. Constructors

Divided into two types: primary constructor and secondary constructors. Primary can only have one, and secondary may have multiple.

If neither constructor is specified, the default is primary constructor with no parameters, and its visibility is public. Primary constructor and INIT code block

1, which is part of the class header, is defined by the constructor keyword. If you do not need to change the visibility of the constructor, you can omit the constructor.

2, which is defined after the class name or generic type (if there is a generic).

3, can't write any code

4, if you want to write code in primary constructor, you need to do it in the INIT code block.

5, its parameters can only be used in the INIT code block and the initialization of class member variables. However, you can define a variable with the same name for the class by using Var or val.

6, if you use only the default constructor, you can add parentheses after the class name or generic (if there is a generic), or write nothing directly, but you must write parentheses if you add the constructor keyword.

Example one, the default constructor

Class demo1{//default constructor--nothing writes
	Fun demo () {
		println (toString ())
	}
}
class Demo2 () {//default constructor-- Write a parenthesis directly, you can write the argument list in parentheses
	fun demo () {
		println (toString ())
	}
}

Class Demo3 constructor () {//must write parentheses
	Fun Demo () {
		println (toString ())
	}
}

//class Demo4 constructor{//do not write parentheses compile failure
//	Fun Demo () {
//		println (toString ())
//	}
//}

Example two, basic use

Class Demo<t> Constructor (t:t) {//specified primary constructor

    init {
        t.tostring ()
    }
} by constructor keyword
Example three, omitting constructor and not omitting constructor:
Fun Main (args:array<string>) {
	var d = Demo ("----")//Instantiate object
	var d2 = Demo2 ("----")//This compile will have an error. Because the Demo2 constructor is private, the outside world cannot access
}

class Demo (t:string) {//Omit constructor keyword

    init {
        t.tostring ()
    }
}
Class Demo2 Private Constructor (t:string) {//The constructor is specified as private, so the constructor keyword

    init {
        t.tostring () cannot be omitted.
    }
}
Example four: Init code block:
Fun Main (args:array<string>) {
	var d = demo ("----")
}

class Demo (t:string) {//Omit constructor keyword C16/>init {
        println (t)//Primary constructor operation in init code block
    }
Example five: Use scope of constructor parameters
Fun Main (args:array<string>) {
	val a = Adapter (Demo ())
}

class demo{
	fun Demo (): string{ Return ' This are from
		demo '
	}
}

Class Adapter (Ctx:demo) {
     val inf = Ctx.demo ()//uses CTX to initialize the member variables of the classes
	 init{
		println (ctx.tostring ())// CTX Use in init code block
	 }
	 Fun Test () {
		println (ctx.tostring ())//compile-time report unresolved reference:ctx-- Because CTX is a parameter in a constructor, it can only be used in variable initialization or init code blocks
	 }
}

If you change the CTX in the test () method to INF, you can either compile it or run it.

Example six: Define a variable with the same name as a constructor parameter

Fun Main (args:array<string>) {
	val a = Adapter (Demo ())
	a.test ()
}

class Demo (s:string= "Default ") {
	Fun demo (): string{return" The This is from
		demo "
	}
}

class Adapter (Val ctx:demo) {// Add a Val or var keyword, the class automatically generates a CTX member variable, so the CTX
	 Fun Test () {
		println (ctx.tostring ())//can be used in each method in the class. Because there is a member variable named CTX in the adapter class
	 }

Reverse compile demo and adapter corresponding class file, as follows:



It's easy to see the difference between adding Var or val before the variable name and not adding it. Secondary constructors

1, you can have multiple

2, defined by constructor

3, if there is a primary constructor, then all secondary must be primary directly or indirectly, and this can be used to refer to other constructors.

4, no matter how many secondary,primary a definition must exist. Example one, specifying a different constructor through this

Fun Main (args:array<string>) {
	Demo1 ("First2", ")
}

class demo1{//default parameterless primary constructor
	init{
		println ("init block")//First executed
	}
	Constructor (a:string) {//its proxy primary, except primary is an
		println ("one a= $a")//The second execution
	}
	
	constructor (a: string,b:string): this (b) {//proxy constructor for a parameter, and pass parameter B to the constructor
		println ("Two a= $a, b= $b")//Final execution
	}

Example two, primary with ginseng

Class Demo1 (d:int) {
	init{
		println (d)
	}
	Constructor (a:string): this (3) {//must be represented through this to primary, At the same time passing parameters, here directly pass the specific parameter value
		println ("one a= $a")
	}
	
	Constructor (a:string,b:string): this (b) {// Passes the value of parameter B to the constructor without passing the specific parameter value
		println ("Two a= $a, b= $b")
	}
}






































Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.