Kotlin Learning Four: Classes and objects in the Kotlin

Source: Internet
Author: User
Tags abstract anonymous class definition constructor modifier modifiers
first, class definition

The class is declared using the Generic keyword class in Kotlin, followed by the class name:

Class Kotlinclass {//  class name Kotlinclass
    //curly braces are the body composition
}

Interface Definition

Interface Ikotlininterface

Single Case

Kotlin uses the object class to modify classes, you can implement a singleton mode,
Java Singleton class:

public class javainstanceclass{
      private Javainstanceclass () {}
      private static Javainstanceclass INSTANCE;
      public static Javainstanceclass getinstance () {
          if (instance==null)
              instance=new javainstanceclass ();
          return INSTANCE;
      }
}

Kotlin single-Case class:

Object kotlininstanceclass{
    //curly braces are class-body constituent
}
second, class modifiers

Class Property Modifiers

    Abstract//Abstraction class  
Final//       class not inheritable, default attribute
enum        //enum class Open//        class inheritable, class default is final
annotation  //Annotation class

class permission Modifier

Private//    only visible in the same file
protected  //In the same file or child class visible public//     All calls are visible
internal   / /visible in the same module

Kotlin class default is final, if you need to define a class that can be inherited, you need to add the open modifier three, the constructor

Main constructor
Defined directly after the class name, using the constructor keyword, the init area corresponds to the constructor's method body:

Class person Constructor (firstname:string) {
    init {
         println ("constructor") ("FirstName is $firstName")
    }
}

or omit the Constructor keyword:
class person (firstname:string) {
    init {
         println ("Constructor") ("FirstName is $ FirstName ")
    }
}

The parameters in the main constructor can be used in the init snippet code, or in the property initialization code of the class body, but not in the method body:

Class Person (firstname:string) {
    init {
         println (' Constructor ') ("FirstName is $firstName")
    }
    var fullname:string = "$firstName"
}

The primary constructor is not required.

Chestnuts:
Create a Runoob class and pass in the site name through the constructor:

Class Runoob  Constructor (name:string) {//  class named Runoob
    //curly braces are the classes that make up
    var url:string = "Http://www.runoob . com "
    var country:string =" CN "
    var siteName = name

    init {
        println (" Initialize site name: ${name} ")
    }

    Fun Printtest () {
        println ("I am a function of a class")}
} fun

Main (args:array<string>) {
    val Runoob =  Runoob ("Rookie tutorial")
    println (runoob.sitename)
    println (runoob.url)
    println (runoob.country)
    Runoob.printtest ()
}

The output is:

Initialize Site name: Rookie Tutorial
Rookie tutorial
http://www.runoob.com
CN I am
a function of class

Secondary constructor

defined in the class body with the constructor keyword:

Class Person {
    Constructor (context:context) {

    }

    constructor (context:context,str:string) {

    }
}

If there is a primary constructor, the secondary constructor defined in the class body is called directly or indirectly using this (XXX) to invoke the main constructor:

Class Person (str:string) {
    Constructor (Context:context): This ("xxx") {

    }

    constructor (Context:context, str:string): This (context) {

    }
}
third, abstract class

Abstraction is one of the characteristics of object-oriented programming, and the class itself, or some members of a class, can be declared abstract. Abstract members do not have a specific implementation in the class.

Note: You do not need to annotate open annotations on abstract classes or abstract members.

Open Class Base {
    open fun F () {}
}

abstract class Derived:base () {
    override abstract fun F ()
}
Iv. Nested Classes

the nested class here is similar to a static nested class in Java.

We can nest classes in other classes to see the following examples:

Class Outer {                  //external class
    private Val bar:int = 1 class
    Nested {             //nested class Fun
        foo () = 2
    }
}

fun Main (args:array<string>) {
    val demo = outer.nested (). Foo ()//Call Format: External class. Nested class Method/property
    println (Demo)    //= = 2
}
Five, internal class

The inner class is represented by using the Inner keyword.

The inner class will have a reference to an object of the external class, so the inner class can access the external classes member properties and member functions.

Class Outer {
    private val bar:int = 1
    var v = "Member property"
    /** nested inner class **/
    inner class Inner {fun
        foo () = Bar  //Access external class member fun
        innertest () {
            var o = this@outer//Get member variable println for external class
            ("inner class can refer to members of external class, for example:" + o.v)
        }
    }
}

Fun Main (args:array<string>) {
    val demo = Outer (). Inner (). Foo ()
    println (Demo)//   1
    val demo2 = Outer (). Inner (). Innertest ()   
    println (DEMO2)   //inner class can refer to members of external classes, for example: member Properties
}

To disambiguate , to access this from an external scope, we use This@label, where @label is a label that refers to this source, such as the this@outer above vi. Anonymous Internal classes

Use an object expression to create an anonymous inner class:

Interface Definition
interface testinterface {fun
    test ()
}
Class Test {
    var v = "Member property" Fun

    setinterface (test:testinterface) {
        test.test ()
    }
} fun

Main ( args:array<string>) {
    var test = Test ()

    /**
     * uses an object expression to create an interface object, an instance of an anonymous inner class.
     */
    Test.setinterface (Object:testinterface {
        override fun Test () {
            println ("Object expression creates an instance of an anonymous inner class")
        }
    })
}
Vii. Properties of the class

Property Definition

Using Val to declare mutable variables, use Val to declare immutable constants:

Class Runoob {
    var name:string = ...
    Val url:string = ...
}

To create an instance of a class:

In Kotlin:
val runoob = Runoob ()

//in Java:
runoob runoob = new Runoob ()

To use a class variable:

Runoob.name           //Use the. Number to refer to
Runoob.url

Getter and Setter

Full syntax for property declarations:

var <propertyname>[: <propertytype>] [= <property_initializer>]
    [<getter>]
    [< Setter>]

Getter and setter are optional

If an attribute type can be inferred from an initialization statement or a member function of a class, the type is omitted, and Val does not allow the setter function to be set because it is read-only.

var allbydefault:int? Error: Requires an initialization statement that implements getter and setter methods by default
var initialized = 1    //Type INT, by default implements Getter and setter Val Simple
: Int?       The type is int, the default implementation getter, but must be initialized in the constructor
val inferredtype = 1   //type int, the default implementation getter

Chestnuts:

The following example defines a person class, contains two mutable variables lastName and No,lastname modifies the getter method, and no modifies the setter method.

Class Person {

    var lastname:string = "Zhang"
        get () = Field.touppercase ()   //Assign variable to uppercase
        set

    var no: Int = +
        get () = field                //back-end variable
        set (value) {
            if (value <) {       ///If the value passed in is less than 10 returns the value
                field = Val UE
            } else {
                field =-1         //If the passed value is greater than or equal to 10 returns-1
            }
        }

    var heiht:float = 145.4f
        Private Set
}

Test Fun
Main (args:array<string>) {
    var Person:person = person ()

    person.lastname = "Wang"

    println ("Lastname:${person.lastname}")

    person.no = 9
    println ("no:${person.no}")

    person.no = 20
    println ("no:${person.no}")

}

The output is:

Lastname:wang
no:9
no:-1

Classes in Kotlin cannot have fields. The backing fields (backend variable) mechanism is provided, the alternate field is declared with the field keyword, and the field keyword can only be used for the accessor of the property, as in the above example:

var no:int =
        10 get () = field                //back-end variable
        set (value) {
            if (value <) {       //) returns the value if the value passed in is less than
                Fiel D = value
            } else {
                field =-1         //If the value passed in is greater than or equal to 10 returns-1
            }
        }

Non-null properties must be initialized at the time of definition, Kotlin provides a scheme that can be deferred for initialization and describes attributes using the Lateinit keyword:

public class MyTest {
    lateinit var subject:testsubject

    @SetUp Fun SetUp () {
        subject = Testsubject ()
    }

    @Test Fun Test () {
        subject.method ()  //dereference directly
    }
}

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.