Kotlin Visibility Modifier

Kotlin visibility modifiers are the special variety of keywords which are wont to make our variable or method restricted for the employment of interface, class, methods, and property of Kotlin within the whole application. These modifiers is used at multiple places like class header or method body.

In Kotlin, we’ve visibility modifiers of 4 different types:

  • public
  • protected
  • internal
  • private

public modifier

A public modifier is  a default modifier in Kotlin which can be accessible from everywhere in the project. If any class, interface etc. are not label with any type of access modifier then that class or  interface etc. are used in public scope by default.

1. public class Example{  
2. }  
3. class Demo{  
4. }  
5. public fun hello()  
6. fun demo()  
7. public val x = 5  
8. val y = 10  

protected modifier

A protected modifier allow us the visibility of class or interface to its class or subclass only. A protected declaration in its subclass can be treated as protected modifier unless it is explicitly changed.

1. open class Base{  
2.     protected val i = 0  
3. }  
4.   
5. class Derived : Base(){  
6.   
7.     fun getValue() : Int  
8.     {  
9.         return i  
10.     }  
11. }  

In Kotlin, we can not declare protected modifier at top level.

Overriding of protected types

1. open class Base{  
2.   open protected val i = 5  
3. }  
4. class Another : Base(){  
5.     fun getValue() : Int  
6.     {  
7.         return i  
8.     }  
9.     override val i =10  
10. }

internal modifier

The internal modifiers are new in Kotlin, this type of modifier is not available in Java. We can declare anything with keyword as internal field. The internal modifier can make the field visible only inside the module in which it has to be implemented.

1. internal class Example{  
2.     internal val x = 5  
3.     internal fun getValue(){  
4.   
5.     }  
6. }  
7. internal val y = 10  

private modifier

A private modifier allows us to access variable ,method or function only within the block in which these properties are declare. The private modifier declaration prevent to access the outside the scope. 

1. private class Example {  
2.     private val x = 1  
3.      private valdoSomething() {  
4.     }  
5. }  

Example of Visibility Modifier

1. open class Base() {  
2. var a = 1 // public by default  
3.     private var b = 2 // private to Base class  
4.     protected open val c = 3  // visible to the Base and the Derived class  
5.     internal val d = 4 // visible inside the same module  
6.     protected fun e() { } // visible to the Base and the Derived class  
7. }  
8.   
9. class Derived: Base() {  
10.     // a, c, d, and e() of the Base class are visible  
11.     // b is not visible  
12.     override val c = 9 // c is protected  
13. }  
14.   
15. fun main(args: Array<String>) {  
16. val base = Base()  
17.     // base.a and base.d are visible  
18.     // base.b, base.c and base.e() are not visible  
19. val derived = Derived()  
20.     // derived.c is not visible  
21. }

Kotlin Inheritance

As we know that Inheritance is an important feature of object oriented programming language. With the help of inheritance we can  inherit the feature of existing class or base or parent class to new class or derived class or child class.

In inheritance the main class is called super class or parent class and the class which inherits the superclass is known as subclass or child class. The subclass contains features of superclass which it has inherit as well as its own.

The concept of inheritance can be applied when two or more classes have same properties and function. It allows code reusability means we can reuse the code again. In Kotlin, the derived class inherits a base class with the help of : operator in the class header 


1. open class Base(p: Int){  
2.   
3. }  
4. class Derived(p: Int) : Base(p){  
5.   
6. }

Let’s suppose we have two different classes “Developer” and “Tester” having the common properties ‘name’,’age’, and ‘salary’ as well as their own separate functionalitiesdoProgram() and fieldWork(). The feature of inheritance allows that we can inherit (Employee) containing the common features.

1. open class Employee(name: String, age: Int, salary: Float) {  
2.     // code of employee  
3. }  
4.   
5. class Developer(name: String, age: Int, salary: Float): Employee(name,age,salary) {  
6.     // code of Developer  
7. }  
8.   
9. class Tester(name: String, age: Int, salary: Float): Employee(name,age,salary) {  
10.     // code of Tester  
11. }  

All Kotlin classes have a common superclass that is “Any”. It is a by default superclass for a class with no supertypes explicitly specified.

Kotlin open keyword

As we know that classes in kotlin are final by default, we  cannot be inherited them simply. We use the open keyword for the class which have to inherit and make it to non-final,

For example:

1. open class Example{  
2. // I can now be extended!  
3. }  

Kotlin Inheriting fields and methods from a class

When we are to inherit a category to derive class, all the fields and functionalities are inherited. we will use these fields and functionalities in derived class.

For example:

1. open class Base{  
2. val x = 10  
3. }  
4. class Derived: Base() {  
5.     fun foo() {  
6. println("x is equal to " + x)  
7.     }  
8. }  
9. fun main(args: Array<String>) {  
10. val derived = Derived()  
11.     derived.foo()   
12. }  

Output:-

x is equal to 10

Kotlin Inheritance and primary constructor

Kotlin Inheritance and primary constructor

There may be a different situation where the base and derived class both having primary constructor in such case the parameters must be  initialized in the primary constructor of base class. Also when a base and derived class both have different numbers of parameters in their primary constructor then base class parameters must be initialized form derived class object.

For example:

1. open class Employee(name: String,salary: Float) {  
2. init {  
3. println("Name is $name.")  
4. println("Salary is $salary")  
5.     }  
6. }  
7. class Programmer(name: String, dept: String, salary: Float):Employee(name,salary){  
8. init {  
9. println("Name $name of department $dept with salary $salary.")  
10.     }  
11.     fun doProgram() {  
12. println("Programming is my passion.")  
13.   
14.     }  
15. }  
16. class Salesman(name: String, dept: String, salary: Float):Employee(name,salary){  
17. init {  
18. println("Name $name of department $dept with salary $salary.")  
19.     }  
20.     fun fieldWork() {  
21. println("Travelling is my hobby.")  
22.   
23.     }  
24. }  
25. fun main(args: Array<String>){  
26. val obj1 = Programmer("Ashu", "Development", 40000f)  
27.     obj1.doProgram()  
28. println()  
29. val obj2 = Salesman("Ajay", "Marketing", 30000f)  
30.     obj2.fieldWork()  
31. } 

Output:-

Name is Ashu.
Salary is 40000.0
Name Ashu of department Development with salary 40000.0.
Programming is my passion.

Name is Ajay.
Salary is 30000.0
Name Ajay of department Marketing with salary 30000.0.
Travelling is my hobby.

Kotlin Inheritance and secondary constructor

There may be some situation where derived class does not have any primary constructor , in such condition it is very important to required to call the base class secondary constructor from derived class with the help of super keyword.

For example

1. open class Patent {  
2.   
3.     constructor(name: String, id: Int) {  
4. println("run  super constructor $name: $id")  
5.     }  
6. }  
7.   
8. class Child: Patent {  
9.   
10.     constructor(name: String, id: Int, dept: String): super(name, id) {  
11.         print(“run children class constructor with property $name, $id, $dept")  
12.     }  
13. }  
14. fun main(args: Array<String>) {  
15. val child = Child("Ashu",101, "Developer")  
16. } 

Output:-

run super constructor Ashu: 101
run children class constructor with property Ashu, 101, Developer

Kotlin Method Overriding

Method overriding simply means providing the specific implementation of method of super class into its subclass class Or we can say that, when subclass try reuse or modifies the method which is in  superclass from subclass,  known as method overriding and it is only possible in inheritance.

KotlinRules of method overriding

  • Method or property which is to be overridden must be open that is non final of Parent class.
  • Base class and drive class have same name of Method.
  • Method must have same parameter as it have in base class.

Example of inheritance without overriding

1. open class Bird {  
2.     open fun fly() {  
3. println("Bird is flying...")  
4.     }  
5. }  
6. class Parrot: Bird() {  
7.   
8. }  
9. class Duck: Bird() {  
10.   
11. }  
12. fun main(args: Array<String>) {  
13. val p = Parrot()  
14.     p.fly()  
15. val d = Duck()  
16.     d.fly()  
17. }  

Output:-

Bird is flying...
Bird is flying...

Let’s do this program with the help of method overridng

Example of Kotlin method overriding

1. open class Bird {  
2.     open fun fly() {  
3. println("Bird is flying...")  
4.     }  
5. }  
6. class Parrot: Bird() {  
7.     override fun fly() {  
8. println("Parrot is flying...")  
9.     }  
10. }  
11. class Duck: Bird() {  
12.     override fun fly() {  
13. println("Duck is flying...")  
14.     }  
15. }  
16. fun main(args: Array<String>) {  
17. val p = Parrot()  
18.     p.fly()  
19. val d = Duck()  
20.     d.fly()  
21. }  

Output:-

Parrot is flying...
Duck is flying...

Kotlin Abstract class

An abstract class can be define when a class which is declared with abstract keyword. We can not instantiate an abstract class. Means, we are unable to create object of abstract class. In abstract class we can also declare  method and properties  non-abstract until they are explicitly declared as abstract.

Declaration of abstract class

1. abstract class A {  
2. var x = 0  
3.     abstract fun doSomething()  
4. } 

Example of abstract class that has abstract method

Let’s see an example, which have an abstract class Car that contains an abstract function run(). The implementation of run() function is defined by its subclass Honda.

1. abstract class Car{  
2.     abstract fun run()  
3. }  
4. class Honda: Car(){  
5.    override fun run(){  
6. println("Honda is running safely..")  
7.    }  
8. }  
9. fun main(args: Array<String>){  
10. val obj = Honda()  
11. obj.run();  
12. } 

Output:-

Honda is running safely..

Kotlin Interface

An interface could be a blueprint of class.Kotlin interface is comparable to Java 8. It contains abstract method declarations additionally as implementation of method..

Defining Interface

An interface is defined using the keyword interface. For example:

1. interface MyInterface {  
2. val id: Int // abstract property  
3.     fun absMethod()// abstract method  
4.     fun doSomthing() {  
5.       // optional body  
6.     }  
7. } 

Why use Kotlin interface?

Following are the reasons to use interface:

  • Using interface supports functionality of multiple inheritance.
  • It has loose coupling.
  • It is used to achieve abstraction.

Subclass extends only one super class but implements multiple interfaces. We can do extension of parent class or interface implementation with the help of (:) operator in their subclass.

Implementing Interfaces

In see an example of implementation of Interface.

1. interface MyInterface  {  
2. var id: Int            // abstract property  
3.     fun absMethod():String    // abstract method  
4.     fun doSomthing() {  
5. println("MyInterface doing some work")  
6.     }  
7. }  
8. class InterfaceImp : MyInterface {  
9.     override var id: Int = 101  
10.     override fun absMethod(): String{  
11. return "Implementing abstract method.."  
12.     }  
13. }  
14. fun main(args: Array<String>) {  
15. val obj = InterfaceImp()  
16. println("Calling overriding id value = ${obj.id}")  
17. obj.doSomthing()  
18. println(obj.absMethod())  
19. }  

Output:

Calling overriding id value = 101
MyInterface doing some work
Implementing abstract method..

You may also like...

0 Comments

No Comment.