Thursday, 11 January 2018

Kotlin: Interfaces

What is an Interface ?
Interfaces are the contracts in the outside world.

What it mean?
Take an example, let us assume, there is a standard for all mobile phones, as per the standard, below are the basic functionality for the mobile phones to provide. 

Vendor1 provides the functionality for the mobile in language JAVA
Vendor2 provides the functionality for the mobile in language C++
Vendor3 provides the functionality for the mobile in language JAVA
Vendor4 provides the functionality for the mobile in language C

that mean all the vendors providing the same functionality, but the way they are providing is different.

One more example is IBM JAVA, Oracle JAVA are providing the functionality for JAVA, but the way they implemented the features is different.

How to define an interface in kotlin?
You can define the interfaces using 'interface' keyword. Interfaces in kotlin are similar to interfaces in Java8.

interface InterfaceName{
 /* Function without body*/
 fun method1()
 
 /* Function with body*/
 fun mehtod2(){
 
 }

}

How to implement an interface?
kotlin class can implement one or more interfaces.

Syntax
class ClassName : Interface1, Interface2...InterfaceN{

}

Find the below working application.


HelloWorld.kt

interface Arithmetic {
 fun sum(a: Int, b: Int): Int
 fun sub(a: Int, b: Int): Int
}

class ArithmeticImpl : Arithmetic {
 override fun sum(a: Int, b: Int): Int {
  return a + b
 }

 override fun sub(a: Int, b: Int): Int {
  return a - b
 }
}

fun main(args: Array<String>) {
 var obj = ArithmeticImpl()
 
 println("Sum of 10 and 20 is : ${obj.sum(10, 20)}")
 println("Sub of 10 and 20 is : ${obj.sub(10, 20)}")
}

Output

Sum of 10 and 20 is : 30
Sub of 10 and 20 is : -10

Can a class implement more than one interface?
yes, a class can implement more than one interfaces.

class ArithmeticImpl : Arithmetic, Message {

}

In the above example, "ArithmeticImpl" class is implementing Arithmetic and Message interfaces.

Find the below working application.


HelloWorld.kt
interface Arithmetic {
 fun sum(a: Int, b: Int): Int
 fun sub(a: Int, b: Int): Int
}

interface Message {
 fun amoutMe(): String
}

class ArithmeticImpl : Arithmetic, Message {
 override fun sum(a: Int, b: Int): Int {
  return a + b
 }

 override fun sub(a: Int, b: Int): Int {
  return a - b
 }

 override fun amoutMe(): String {
  return "ArithmeticImpl class"
 }
}

fun main(args: Array<String>) {
 var obj = ArithmeticImpl()

 println("Sum of 10 and 20 is : ${obj.sum(10, 20)}")
 println("Sub of 10 and 20 is : ${obj.sub(10, 20)}")
 println(obj.amoutMe())
}

Output

Sum of 10 and 20 is : 30
Sub of 10 and 20 is : -10
ArithmeticImpl class

Can I define properties in interface?
Yes, you can define properties in interfaces. Properties can be abstract (or) have definition.


HelloWorld.kt

interface DemoInterface {
 var variable1: String
 val variable2: String
  get() = "Hello World"
}

class MyClass : DemoInterface {
 override var variable1: String = "Hello"
}

fun main(args: Array<String>) {
 var obj = MyClass()

 println("variable1 : ${obj.variable1}")
 println("variable2 : ${obj.variable2}")
}

Output

variable1 : Hello
variable2 : Hello World



Previous                                                 Next                                                 Home

Wednesday, 10 January 2018

Kotlin: Inner classes

Inner classes are like nested class, only difference is you can access the members of outer class from inner class.

How to define inner class?
Inner class is defined using the keyword ‘inner’.

How to define object of inner class?
var innerObj = Outer().Inner()

InnerDemo.kt
class Outer {

 fun printMsg() {
  println("Inside Outer class")
 }

 inner class Inner {
  fun printMsg() {
   println("Inside Inner class")
  }
 }
}

fun main(args: Array<String>) {
 var outerObj = Outer()
 var innerObj = Outer().Inner()

 outerObj.printMsg()
 innerObj.printMsg()
}

Output
Inside Outer class
Inside Inner class

You can able to access the member variables of outer class from inner class.


InnerDemo.kt

class Outer {
 private var x = 10

 inner class Inner {
  fun getX() = x
 }
}

fun main(args: Array<String>) {
 var innerObj = Outer().Inner()

 var x = innerObj.getX()

 println("x = $x")
}

Output

x = 10


Previous                                                 Next                                                 Home

Tuesday, 9 January 2018

Kotlin: Nested classes

A class can be nested in other class.

Ex
class Outer {

         class Nested {

         }
}

How to create an object to nested class?
var obj = Outer.Nested()

NestedClass.kt
class Outer {

 fun printMsg() {
  println("Inside Outer class")
 }

 class Nested {
  fun printMsg() {
   println("Inside Nested class")
  }
 }
}

fun main(args: Array<String>) {
 var outerObj = Outer()
 var nestedObj = Outer.Nested()

 outerObj.printMsg()
 nestedObj.printMsg()
}

Output
Inside Outer class
Inside Nested class

Can I access the member variables defined in outer class from nested class?
No, you can’t access the member variables defined in outer class from nested class.


NestedDemo.kt

class Outer {
 private var x = 10

 class Inner {
  fun getX() = x
 }
}

When you try to compile above program, you will end up in below error.

Unresolved reference: x


Previous                                                 Next                                                 Home

Monday, 8 January 2018

Kotlin: Calling super class methods

By using super keyword, you can call super class methods.

Syntax
super.methodName

SuperDemo.kt

open class BaseClass {
 open fun printMsg() {
  println("Hello Base class")
 }
}

open class DerivedClass : BaseClass() {
 override fun printMsg() {
  println("Hello Derived class")
  super.printMsg()
 }
}

fun main(args: Array<String>) {
 var obj = DerivedClass()

 obj.printMsg()
}

Output

Hello Derived class
Hello Base class


Previous                                                 Next                                                 Home

Saturday, 6 January 2018

Kotlin: Overriding properties

In my previous post, I explained how to override methods, overriding of properties is similar to overriding of methods.

Below step by step procedure explains, how to override a property.

Step 1: Define a variable with open modifier in Base class.
open class BaseClass {
         open var name: String = "Base Class"
}

Step 2: In sub class redefine the variable with same name using override modifier.
open class DerivedClass : BaseClass() {
         override var name: String = "Derived Class"
}

Find the below working application.

Inheritance.kt
open class BaseClass {
 open var name: String = "Base Class"
}

open class DerivedClass : BaseClass() {
 override var name: String = "Derived Class"
}

fun main(args: Array<String>) {
 var obj = DerivedClass()

 println("name : $obj.name")
}

Output

name : Derived Class

Can I override a val property with var property?
Yes, you can override a val property with a var property.


Inheritance.kt

open class BaseClass {
 open val name: String = "Base Class"
}

open class DerivedClass : BaseClass() {
 override var name: String = "Derived Class"
}

fun main(args: Array<String>) {
 var obj = DerivedClass()

 println("name : ${obj.name}")
}

Can I override a var property with val property?
No, you can’t override a var property with val property.

Inheritance.kt

open class BaseClass {
 open var name: String = "Base Class"
}

open class DerivedClass : BaseClass() {
 override val name: String = "Derived Class"
}

fun main(args: Array<String>) {
 var obj = DerivedClass()

 println("name : ${obj.name}")
}

When you try to compile above program, you will end up in below compilation error.


ERROR: Var-property public open val name: String defined in DerivedClass cannot be overridden by val-property public open var name: String defined in BaseClass (6, 11)





Previous                                                 Next                                                 Home

Kotlin: Overriding methods

By using ‘override’ keyword, you can override the methods of base class. By default all the methods in a class are final (not overridable), you can make them overridable by using ‘open’ keyword’.

Override.kt
open class BaseClass{
 open fun sayHello(){
  println("******Hello World******")
 }
}

class DerivedClass : BaseClass(){
 override fun sayHello(){
  println("@@@@Hello World@@@@@")
 }
}
fun main(args: Array<String>) {
 var obj = DerivedClass()
 
 obj.sayHello()
 
}


Output
@@@@Hello World@@@@@


As you observe above snippet, DerivedClass inhrites from BaseClass. sayHello() method of DerivedClass override the sayHello() method of BaseClass using override keyword.

A method defined with the keyword ‘override’ is itself open, so the child classes of the DerivedClass, can override this method.


Override.kt
open class BaseClass {
 open fun sayHello() {
  println("******Hello World******")
 }
}

open class DerivedClass : BaseClass() {
 override fun sayHello() {
  println("@@@@Hello World@@@@@")
 }
}

class ChildDerivedClass : DerivedClass() {
 override fun sayHello() {
  println("####Hello World####")
 }
}

fun main(args: Array<String>) {
 var obj = ChildDerivedClass()

 obj.sayHello()

}

Output
####Hello World####

If you want to prohibit the re-overriding, use the keyword final.

Ex
open class DerivedClass : BaseClass() {
         final override fun sayHello() {
                 println("@@@@Hello World@@@@@")
         }
}


Override.kt
open class BaseClass {
 open fun sayHello() {
  println("******Hello World******")
 }
}

open class DerivedClass : BaseClass() {
 final override fun sayHello() {
  println("@@@@Hello World@@@@@")
 }
}

class ChildDerivedClass : DerivedClass() {
 override fun sayHello() {
  println("####Hello World####")
 }
}

fun main(args: Array<String>) {
 var obj = ChildDerivedClass()

 obj.sayHello()

}

When you try to compile above program, kotlin compiler throws below error.

'sayHello' in 'DerivedClass' is final and cannot be overridden





Previous                                                 Next                                                 Home

Thursday, 4 January 2018

Kotlin: Inheritance

Inheritance is the concept of re usability. Object of one class can get the properties and methods of object of another class by using inheritance.

By using inheritance, you can create new class by extending the existing class. The new class is called derived class and the existing class is called base class.



Example
open class BaseClass{

}

class DerivedClass : BaseClass{

}


By default, all the classes in kotlin are final. To make these class inheritable, you should use the keyword ‘open’.


Let’s see inheritance feature by an example. In every organization, there are two kinds of employees.
a.   Permanent Employees
b.   Contract Employees

Both the permanent and contract employees share properties like firstName, lastName and id. Where as contract employees has separate payroll company. We can place these common properties (firstName, lastName and id) in separate class Employee and make the classes PermanentEmployee and ContractEmployee inherit these properties from the common base class Employee.

open class Employee {

}

class PermanentEmployee : Employee {

}

class ContractEmployee : Employee {

}

Find the below working application.


Inheritance.kt
open class Employee {
 var firstName: String = ""
 var lastName: String = ""
 var id: String = ""

 constructor(firstName: String, lastName: String, id: String) {
  this.firstName = firstName
  this.lastName = lastName
  this.id = id
 }

 open fun getEmployee(): String {
  return "firstName : $firstName, lastName: $lastName, id: $id"
 }

}

class PermanentEmployee : Employee {
 var healthInsuranceNumber = ""
 var salary: Double = 0.0

 constructor(firstName: String, lastName: String, id: String, healtInsuranceNumber: String, salary: Double) : super(firstName, lastName, id) {
  this.healthInsuranceNumber = healtInsuranceNumber
  this.salary = salary
 }

 override fun getEmployee(): String {
  return super.getEmployee() + ", healthInsuranceNumber: $healthInsuranceNumber, salary: $salary"
 }

}

class ContractEmployee : Employee {
 var payRollCompany = "ABC"

 constructor(firstName: String, lastName: String, id: String, payRollCompany: String) : super(firstName, lastName, id) {
  this.payRollCompany = payRollCompany
 }

 override fun getEmployee(): String {
  return super.getEmployee() + ", payRollCompany: $payRollCompany"
 }
}


fun main(args: Array<String>) {
 var emp = PermanentEmployee("krishna", "Gurram", "123", "health3425", 56789.01)

 println(emp.getEmployee())
}


Output
firstName : krishna, lastName: Gurram, id: 123, healthInsuranceNumber: health3425, salary: 56789.01

constructor(firstName: String, lastName: String, id: String, healtInsuranceNumber: String, salary: Double) : super(firstName, lastName, id)
If super class don’t have default constructor, then all the sub class constructors must call the super class constructor explicitly.

By default, all the functions and classes are not inheritable (final), to make them inheritable, you should use the keyword ‘open’.

open class Employee {

         open fun getEmployee(): String {
                 return "firstName : $firstName, lastName: $lastName, id: $id"
         }

}

To override a function of super class, you should use override keyword.

class PermanentEmployee : Employee {

         override fun getEmployee(): String {
                 return super.getEmployee() + ", healthInsuranceNumber: $healthInsuranceNumber, salary: $salary"
         }

}

Important Points
a.   If the class has a primary constructor, the base type can (and must) be initialized right there, using the parameters of the primary constructor.


b.   If the class has no primary constructor, then each secondary constructor has to initialize the base type using the super keyword, or to delegate to another constructor which does that. Note that in this case different secondary constructors can call different constructors of the base type:


Previous                                                 Next                                                 Home