Java to Kotlin part -2

Hello Everyone,

In this post, we will see object-oriented syntex and features in Kotlin. for other basic detail please visit the part-1 tutorial to make yourself comfortable.

let’s jump into code!

#using class

Java

class Customer {
}

Kotlin

class Customer {
}
//or if the class has no body then curley braces can be omitted
class Customer

 

#using constructor including primary and secondary 

Java

class Customer {

    String name;

    Customer() {}

    Customer(String name)
    {
        //TODO
    }
}

Kotlin

class Customer() {

    lateinit var name: String

    constructor(name: String) : this()
    {
        //TODO
    }
}

#using instance of class

Java

Customer customer = new Customer();
//or
Customer customer1 = new Customer("Test");

Kotlin

val customer  = Customer()
//or
val customer1 = Customer("Test")

#using inheritance 

Java

public class Base {

    Base(int p)
    {
        //TODO
    }
}
public class Derived extends Base{

    Derived(int p) {
        super(p);
    }
}

Kotlin

open class Base(p: Int)
class Derived(p: Int) : Base(p)

#using method overriding

Java

public class Base {

   final void v() {}
   void nv() {}
}
public class Derived extends Base{

    @Override
    void nv() {
        super.nv();
    }
}

Kotlin

open class Base {
    open fun v() {}
    fun nv() {}
}
class Derived() : Base() {
    override fun v() {}
}

#using static methods

Java

class Customer {

   static String name = "Test";
}

Kotlin

class Customer {

    companion object {
         var name : String = "Test"
    }
}

 

Thanks for reading 🙂

2 thoughts on “Java to Kotlin part -2

Leave a comment