Kotlin Kotlin OOP 2 — Questions and Answers
Question 1: What is an object declaration in Kotlin?
- A class with no properties
- A singleton instance created using the `object` keyword (Correct answer)
- An anonymous class
- A static inner class
Correct answer: A singleton instance created using the `object` keyword
An `object` declaration in Kotlin creates a singleton — a class with exactly one instance, initialized lazily on first access.
Question 2: How do you implement an interface in Kotlin?
- Using the `implements` keyword
- Using a colon followed by the interface name (Correct answer)
- Using the `extends` keyword
- Using the `@interface` annotation
Correct answer: Using a colon followed by the interface name
Kotlin uses a colon (`:`) for both class inheritance and interface implementation, followed by the interface or superclass name.
Question 3: What does the `override` keyword do in Kotlin?
- Hides the parent method
- Explicitly marks a method as overriding a parent class or interface member (Correct answer)
- Prevents further overriding
- Creates a new method
Correct answer: Explicitly marks a method as overriding a parent class or interface member
The `override` modifier is required in Kotlin to explicitly indicate that a method overrides a member from a parent class or interface.
Question 4: What is a primary constructor in Kotlin?
- The first constructor listed in a class
- A constructor declared in the class header (Correct answer)
- A constructor with no parameters
- A constructor that calls super()
Correct answer: A constructor declared in the class header
The primary constructor is declared directly in the class header after the class name and can include property declarations.
Question 5: What is the purpose of `init` block in a Kotlin class?
- To declare properties
- To run initialization code when an instance is created (Correct answer)
- To define static members
- To override toString
Correct answer: To run initialization code when an instance is created
The `init` block contains initialization code that runs immediately after the primary constructor when a class instance is created.
Question 6: What is an abstract class in Kotlin?
- A class that cannot have properties
- A class that cannot be instantiated and may have abstract members (Correct answer)
- A class with only one subclass
- A class with no constructor
Correct answer: A class that cannot be instantiated and may have abstract members
An `abstract` class in Kotlin cannot be instantiated directly and may contain abstract members that subclasses must implement.
What is an object declaration in Kotlin?