Classes, constructors and properties
Classes:
Classes are declared with the word class:
You can declare a class without body:
Constructors:
A class can have a primary constructor and one or more secondary constructor. The primary is part of the class header:
You can omit the keyword constructor if the primary constructor doesn’t have any annotations or visibility modifiers:
The primary constructor can’t have any code and the initialization code can be placed in a init block.
You can declare properties and initialize them in the primary constructor like this:
Secondary constructors:
Secondary constructor has the keyword constructor.
If the class has a primary constructor, the secondary constructors have to delegate to the primary constructor. To delegate to another constructor we use the keyword this.
If you don’t want to declare any constructor and you don’t want your class to have a public constructor (if you don’t declare any constructor, a no arguments and public constructor is generated for the class) you can make your constructor private:
To instance classes:
To create an instance of a class, we don’t use the keyword new as Java. You just have to call the constructor as a common function.
Properties:
Declaring properties:
You can declare them as mutable, using var or read-only using val.
You can use the properties just referring them by the name:
Getters and setters:
Getters and setters are optional but you can write them to give your properties an especial behaviour.