CodeBlanks Logo Icon CodeBlanks

class

Learn to define classes with class.

class: define a new type

A class defines a new type; inside it, data and behaviour live together. In its simplest form a class can have an empty body.

class Person

val p = Person()

This declaration creates a new type called Person. The call Person() creates an instance of this type. Class names usually start with an uppercase letter; this is a common convention.

Creating instances

To create an instance of a class you call the class name with parentheses. An instance is a concrete object of that class.

val p = Person()
val q = Person()
// p and q are different instances

Each call creates a new object; two instances are independent. You assign the instance to a val variable to reuse it. In later lessons you will add properties and behaviour to the instance.

Practice Define a class and create an instance

Define an empty-bodied class called Person. In main create an instance and print "Person ready" with println.

Starter code

Main.kt
fun main() {
    // Define a Person class and create an instance, print ready
}

Sample solution

Main.kt
class Person

fun main() {
    val p = Person()
    println("Person ready")
}

Expected output

Kişi hazır

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does class Person define?

  • A function
  • A template type Correct answer
  • A constant
  • An interface

Explanation: class defines a new type as a template.

2 Fill in the blank: declare a class

Question
class ____ { }
Answer
class Person { }

Explanation: class Person declares a new type.

3 Match concept to meaning

Term Meaning
class Template
Person() Instance
Person Type name
val p Variable

All lessons in Beginner