Kotlin
Summary - Classes
Combine primary/secondary constructors and companion object to write a Point class.
Summary - Classes
In this group you learned primary and secondary constructors, val/var properties, lateinit, by lazy and companion object. These are the building blocks of class definitions in Kotlin.
Now you will combine them: a class initialized with a primary constructor, opened with a secondary constructor, and exposing a factory through a companion object. This structure is the foundation of real-world models; later, inheritance and interfaces will build on it.
Exercise Combine the Point class
Define a class named Point. Its primary constructor takes val x: Int, val y: Int. Add a secondary constructor that takes a single value: Int and delegates with this(value, value). Add a companion object with a factory method fun origin() = Point(0, 0). In main create two instances with Point(5) and Point.origin(), then print each one's x and y values.
Show example solution
class Point(val x: Int, val y: Int) {
constructor(value: Int) : this(value, value)
companion object {
fun origin() = Point(0, 0)
}
}
fun main() {
val p = Point(5)
val o = Point.origin()
println("p: ${p.x}, ${p.y}")
println("o: ${o.x}, ${o.y}")
}
What comes next?
You learned the class structure. In the next groups you will share code between classes with inheritance, define contracts with abstract classes and specify shared behavior with interfaces.
This group combined primary/secondary constructors, val/var properties, lateinit, by lazy and companion object. These are the core of Kotlin object-oriented programming. Next you will explore inheritable classes with open and method overriding with override.
Exercise Define the Rectangle class
Define a class named Rectangle. Its primary constructor takes val w: Int, val h: Int. Add an init block that writes println("Rectangle created: $w x $h"). Add a fun area() = w * h method. Inside a companion object add a factory method fun square(side: Int) = Rectangle(side, side). In main instantiate with Rectangle.square(4) and print the result of area().
Show example solution
class Rectangle(val w: Int, val h: Int) {
init {
println("Rectangle created: $w x $h")
}
fun area() = w * h
companion object {
fun square(side: Int) = Rectangle(side, side)
}
}
fun main() {
val s = Rectangle.square(4)
println(s.area())
}
Test yourself
-
The Point.origin() call shows where origin is defined. Where is it?
- On the instance
- In the init block
- Inside the companion object
- As an extension
Show answer
Inside the companion object — Methods in the companion object are called through the class name.
-
Complete the factory method call
val p = Point.____()
println(p.x)
Show answer
val p = Point.create()
println(p.x)
Next lesson: open