Kotlin Kotlin OOP 1 — Questions and Answers
Question 1: Which keyword is used to define a class in Kotlin?
- object
- struct
- class (Correct answer)
- type
Correct answer: class
The `class` keyword is used to define a class in Kotlin, just as in Java.
Question 2: What is a data class in Kotlin?
- A class that stores only primitive types
- A class that automatically generates equals, hashCode, toString, and copy (Correct answer)
- A class used only for database models
- A class with no methods
Correct answer: A class that automatically generates equals, hashCode, toString, and copy
A `data class` in Kotlin automatically generates `equals()`, `hashCode()`, `toString()`, `copy()`, and `componentN()` functions based on the primary constructor parameters.
Question 3: How do you prevent a Kotlin class from being subclassed?
- Using the `private` modifier
- Using the `sealed` modifier
- Using the `final` modifier
- Kotlin classes cannot be subclassed by default (Correct answer)
Correct answer: Kotlin classes cannot be subclassed by default
In Kotlin, all classes are `final` by default and cannot be subclassed unless explicitly marked with `open`.
Question 4: What is a companion object in Kotlin?
- An object that follows another object
- A singleton object associated with a class that allows static-like members (Correct answer)
- A secondary constructor
- An anonymous class
Correct answer: A singleton object associated with a class that allows static-like members
A `companion object` is a singleton tied to a class, allowing you to define members accessible via the class name without an instance.
Question 5: Which keyword allows a Kotlin class to be inherited?
- abstract
- open (Correct answer)
- public
- override
Correct answer: open
The `open` keyword must be added to a Kotlin class to allow it to be subclassed, since classes are final by default.
Question 6: What is a sealed class in Kotlin used for?
- Preventing any instantiation
- Restricting class hierarchies to a fixed set of subclasses (Correct answer)
- Creating singletons
- Enabling multiple inheritance
Correct answer: Restricting class hierarchies to a fixed set of subclasses
A `sealed class` restricts its subclasses to be defined in the same file, enabling exhaustive `when` expressions over class hierarchies.
Which keyword is used to define a class in Kotlin?