encapsulation in Kotlin

By | October 23, 2017

Encapsulation in Kotlin:

//Link of my previous tutorial about Object oriented programming in Kotlin . Complete below part first to better understand //

  1. Kotlin OOP part 1
  2. Kotlin OOP part 2
  3. Kotlin OOP part 3
  4. Kotlin OOP part 4

There are four visibility modifiers in Kotlin. private, protected, internal and public. We learn every part step by step with a basic code example.


In this example code I am not using any access modifier . basic rules of access modifier:

  • If you not provide any access modifier , public is used by default that means your declaration visible everywhere
  • if you make a declaration private means it will be visible inside this class  outer world can not access it
  • protected only visible its own class and its child class . ( we discuss it later)
  • if you make it internal it only visible in this package only

In object oriented programming sense field level data or attribute or property must be private . now we modify our previous example below format :


now see our code field level data is protected now . In our example Client don’t need employee first , middle or last name individually . Management only need employee full name or reverse name.

if now we want to modified employee firstName it return compile time error cause private data can not access outside of this class . It is called the encapsulation of object oriented programming .

Filed level data first , middle, last name only set when object is born or created others time filed level value can not modified.

If our client tell me he/she need mechanism to change first name and need specific user last name. This type of feature setter getter  is the best option .


setter method get data from parameter then change data . getter method only return data .

this keyword : this is a special keyword which is used to  refer this class property or method whatever its modifier . details of this keyworkd


no more today practice practice practice . more and more practice developed your understand and thinking

Leave a Reply