Kotlin Kotlin Classes and Object-Oriented Programming 1 — Questions and Answers
Question 1: What is a data class in Kotlin?
- A class that stores only primitive types
- A class that automatically generates equals, hashCode, copy, and toString (Correct answer)
- A class that cannot be inherited
- A class used only for database storage
Correct answer: A class that automatically generates equals, hashCode, copy, and toString
Kotlin data classes automatically generate `equals()`, `hashCode()`, `toString()`, `copy()`, and component functions based on constructor properties.
Question 2: What keyword makes a Kotlin class open for inheritance?
- abstract
- extends
- open (Correct answer)
- inheritable
Correct answer: open
Kotlin classes are final by default; the `open` keyword must be added explicitly to allow a class to be subclassed.
Question 3: Which Kotlin class type cannot be instantiated and may have abstract members?
- sealed
- data
- abstract (Correct answer)
- inner
Correct answer: abstract
An `abstract` class cannot be instantiated directly and may contain abstract members that subclasses must implement.
Question 4: What is a companion object in Kotlin?
- An object that accompanies a coroutine
- A singleton object declared inside a class that holds class-level members (Correct answer)
- A helper class for data serialization
- An object that implements multiple interfaces
Correct answer: A singleton object declared inside a class that holds class-level members
A companion object is a singleton tied to its enclosing class, used to hold factory methods and constants accessible via the class name.
Question 5: How do you declare a primary constructor in Kotlin?
- Using a `constructor()` block inside the class body
- Using parameters directly after the class name (Correct answer)
- Using `init` keyword before the class name
- Kotlin does not support primary constructors
Correct answer: Using parameters directly after the class name
In Kotlin, the primary constructor is declared directly after the class name using parentheses, with optional `val`/`var` to declare properties.
Question 6: What is a sealed class in Kotlin used for?
- Encrypting class data
- Restricting class hierarchies to a defined set of subclasses (Correct answer)
- Preventing serialization
- Allowing multiple inheritance
Correct answer: Restricting class hierarchies to a defined set of subclasses
A sealed class restricts its subclasses to be defined in the same file, enabling exhaustive `when` expressions over its hierarchy.
What is a data class in Kotlin?