Friday, July 14, 2017

Kotlin OOP : Constructor

Welcome to kotlin Series


Kotlin OOP series:
  1. OOP Basic
  2. Constructor
  3. Inheritance
  4. Method Overriding

This is the second post about Kotlin OOP Concept. In the previous post,  Kotlin OOP: Basic
we talk about a basic opp concept.
In this post, we are going to litter deeper.
Let's start-
From the previous post, we create an Apple class like previous.
let do this-
private class Apple(color:String,shape:String){

  var color:String? = null
  var shape:String? = null

  init {
  //println("Color: $color")
  //println("Shape: $shape")

  this.color = color
  this.shape = shape
  }

  fun GetColor():String?{
  return this.color
  }

  fun GetShape():String?{
  return this.shape
  }

}
In this class, we are working with the primary constructor. But If we have another option to working with the second constructor. Just like Java. How can I do this? Let's start- Let's make the primary constructor empty
private class Apple3(){
}
and declarer secondary constructor like below-
constructor(color:String,shape:String): this() {
}
Now declare class two class variable and assign it in the constructor.
var color:String? = null
var shape:String? = null
assign it-
//second constrictor
constructor(color:String,shape:String): this() {
  this.color = color
  this.shape = shape
}
Greater and setter method already there Check full class code-
private class Apple(){

  var color:String? = null
  var shape:String? = null

  //second constrictor
  constructor(color:String,shape:String): this() {
  this.color = color
  this.shape = shape
  }

  fun GetColor():String?{
  return this.color
  }

  fun GetShape():String?{
  return this.shape
  }

}
test this on the Main method-
fun main(args: Array<String>){
  val apple =Apple3("red","oval")

  println("Color: ${apple.GetColor()} Shape: ${apple.GetShape()}")
}
output-
Color: red Shape: oval
This is very similar to Java code. But if you are using this secondary constructor. you can not create a variable like the primary constructor.

This is a very smaller post. In this post we cover constructor. Some you need the secondary constructor and some time you need the primary constructor. If you come from Java then you should go through the secondary constructor. Then it looks link java. So you feel easy to learn Kotlin. Keep learning.

Thank you for reading this post.
Happy coding.

About Author:

I am Shudipto Trafder,
Since 2015, I write android code. I love to implement new ideas. I use java and also kotlin. Now I am learning Flutter. I love to learn new things and also love to share. And that is the main reason to run this blog.


Let's Get Connected: Facebook Twitter Linkedin Github

No comments :