Kotlin Class & Object
Class is blueprint and object is real time entity of class that are use class properties and capable to execute of class methods. When we define class object and run source code by compiler, then class constructor are create dynamic memory to class instance variable and assign this reference to class objects. Object are used to access existing class method. There can be defined by using of this syntax.
type objectName = ClassConstructor(parameter)
type: type are indicate behavior of objects. val is an define immutable object that means that are cannot holds other instance reference of class. var is mutable they are created mutable object.
Constructor : Constructor are important part of class, that are create new memory to class instance variable and set initial values. And it will returning the reference of instance. That reference are store by objects.
Let see an example to understand class object concept.
//Define class
class Employee{
//Class data member
var name : String
var typeInfo : String
var salary : Double
//Class secondary constructor
//Set initial value
constructor(name:String,typeInfo:String,salary:Double) {
this.typeInfo = typeInfo
this.salary= salary
this.name = name
}
fun details(){
println("\nName : $name")
println("Type : $typeInfo")
println("Salary : $salary")
}
}
fun main(args: Array<String>) {
//Create objects of Employee class
val objOne = Employee("Smith","Driver",10000.6)
val objTwo = Employee("Ruby","Teacher",25000.53)
val objThree = Employee("Joy","Software Developer",75000.23)
objOne.details()
objTwo.details()
objThree.details()
}

In this example there are three objects of employee class. and each object are hold the reference of instance, and inside class instance includes class variables. So each objects of in this situation deal with seperate class instance. And class detail() method are displaying the associative objects values.
Name : Smith
Type : Driver
Salary : 10000.6
Name : Ruby
Type : Teacher
Salary : 25000.53
Name : Joy
Type : Software Developer
Salary : 75000.23
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment