Class Basics
In this page:
Declaring a Simple Class
A class groups related data and behavior under one name, defined with the class keyword. Even a class with no properties or methods can be declared and instantiated.
Example: Declaring a Simple Class
class Greeter {
fun greet() {
println("Hello from Greeter!")
}
}
fun main() {
val greeter = Greeter()
greeter.greet()
}
Login to try C/C++/Java/PHP code in the editor
Properties in the Primary Constructor
Declaring parameters with val or var directly in the class's parentheses creates properties automatically, avoiding the need to write separate field declarations and assignments.
Example: Properties in the Primary Constructor
class Dog(val name: String, val breed: String)
fun main() {
val dog = Dog("Rex", "Labrador")
println("${dog.name} is a ${dog.breed}")
}
Login to try C/C++/Java/PHP code in the editor
Creating Instances
An instance of a class is created by calling its name like a function, passing arguments that match its primary constructor's parameters.
Note: No new keyword is needed in Kotlin, unlike Java.
Example: Creating Instances
class Point(val x: Int, val y: Int)
fun main() {
val p1 = Point(1, 2)
val p2 = Point(3, 4)
println("p1=(${p1.x}, ${p1.y}), p2=(${p2.x}, ${p2.y})")
}
Login to try C/C++/Java/PHP code in the editor
Member Functions
Functions declared inside a class body are member functions (methods) that operate on that instance's own properties, accessible via this implicitly.
Example: Member Functions
class Circle(val radius: Double) {
fun area(): Double = Math.PI * radius * radius
}
fun main() {
val circle = Circle(3.0)
println("Area: ${circle.area()}")
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the
classkeyword needs a following pair of parentheses()for a primary constructor even when it has parameters, or omitting them entirely if there are none. - Not realizing that properties declared in the primary constructor with
val/varautomatically become accessible class members. - Creating an object but forgetting the
()when calling the constructor, e.g. writingDoginstead ofDog().
- A class is declared with the
classkeyword followed by a name and, optionally, a primary constructor. - Properties declared with
val/varinside the constructor parentheses become class members automatically. - An object of a class is created by calling its constructor like a function:
ClassName(...). - Kotlin classes are
final(cannot be subclassed) by default unless markedopen.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: