You are here
Home > Kotlin

Kotlin: Classes and Primary Constructor

kotlin

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

}

output:

Explanation:

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.

Leave a Reply

Top