Kotlin: Classes and Primary Constructor
In this post we will learn about classes, primary constructor in kotlin with example.
- Class is main building block of object-oriented programming language.
- same as java In kotlin also classes are created using class keyword.
- If you not specify access level it will be public by default.
- Class allows as to create our own datatype by grouping together methods and variables.
- The class declaration in kotlin contains the class name, and primary constructor.
- A class can have a primary constructor and one or many secondary constructors.
- The primary constructor cannot contain any code. Initialization code can be placed in initializer blocks, which are prefixed with the init keyword:
- If the constructor has annotations or visibility modifiers, the constructor keyword is required, and the modifiers go before it:
class Employee public @Inject constructor (name: String)
- For creating instance of class in kotlin we not use a new
Val/var variable_name=class_name (param1, param2,….)
Example: use of primary constructor
We declare a class phone that has primary constructor it accepts company, price, storage parameters. We have to use init method for initializing this parameter. If we have to use this parameter outside the init method redeclare it, and use. We declare two functions getprice() and getstorage() to return price and storage respectively.
Keep Visiting TechwithR.com for more upcoming top technical articles and also see my new blog Mag4info. and for kotlin tutorial also see my blog kotlin category.
You can also by SQL 70-761 book write by me from Amazon.
You can also by Kotlin Book write by me from Amazon.