Calling the Kotlin class

In this section, we will see how to call the Kotlin class in Java. Create a Shape class in Kotlin with three properties, height, width, and area, and two functions, shapeMessage and draw:

class Shape(var width : Int, var height : Int , val shape: String) {

var area : Int = 0
fun shapeMessage(){
println("Hi i am $shape, how are you doing")
}
fun draw() {
println("$shape is drawn")
}

fun calculateArea(): Int {
area = width * height
return area
}
}

We can create an instance of the Kotlin class in the same way as we create an instance of a normal Java class. See the following example:

class FromKotlinClass {

public void callShpaeInstance()
{
Shape shape = new Shape(5,5,"Square");

shape.shapeMessage();
shape.setHeight(10);
System.out.println(shape.getShape() + " width " + shape.getWidth());
System.out.println(shape.getShape() + " height " + shape.getHeight());
System.out.println(shape.getShape() + " area " + shape.calculateArea());

shape.draw();
}
}

Create a shape instance by adding constructor parameters. We can use the shape instance to access all class properties by using getter and setter methods. We can also call the shapeMessage or draw functions of the Shape class using the shape instance. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.97.53