You are here
Home > Kotlin

Kotlin: Classes and Primary Constructor


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.

Class Employee




  • 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
  • Syntax:

Val/var variable_name=class_name (param1, param2,….)

Example: use of primary constructor

class phone(Company:String,Price:Double,Storage:String)
var Price:Double?=null;
var Storage:String?=null;

init {
fun getprice():Double?
return this.Price;
fun getstorage():String?
return this.Storage;
fun main(args:Array<String>)
var s=phone(“XYZ”,16000.0,”16GB”);
var r=phone(“ABC”,9000.0,”34Gb”);
println(“storage =”+r.getstorage());




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 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.

Leave a Reply