CH 3 - Classes and objects Flashcards
what is a class
A class in Kotlin is a blueprint for creating objects. It defines the properties (data) and methods (behaviors) that its object instances will have.
What is the difference between a class and an object instance in Kotlin?
A class is the blueprint, while an object instance is a specific realization of that class with actual values for its properties.
Explain the purpose of a constructor in Kotlin.
constructor initializes an object when it is created. Kotlin classes can have primary constructors (defined in the class header) and secondary constructors.
What is the role of the init block in Kotlin classes?
the init block is used to initialize code that needs to run when an object is created. It serves as the body of the primary constructor.
How can you make a Kotlin class subclassable?
sue the open keyword to allow subclassing, as Kotlin classes are final by default.
What is a data class, and what features does it provide automatically?
A data class is a special class used to store data. It automatically generates methods like toString(), equals(), hashCode(), and copy().
Define a simple class in Kotlin named Car with properties brand, model, and a method startEngine(). Then, create an object instance and call the startEngine() method.
class Car(val brand: String, val model: String) {
fun startEngine() {
println(“The engine of $brand $model has started.”)
}
}
val myCar = Car(“Toyota”, “Corolla”)
myCar.startEngine()
Create a class Rectangle with a primary constructor that takes the length and width of the rectangle. Include an init block to print the area when an object is created.
class Rectangle(val length: Int, val width: Int) {
init {
println(“Area of the rectangle is ${length * width}”)
}
}
val rect = Rectangle(10, 5)
// Output: Area of the rectangle is 50
Write a Kotlin class Person with properties firstName and lastName. Use a custom getter for a fullName property that combines firstName and lastName.
class Person(val firstName: String, val lastName: String) {
val fullName: String
get() = “$firstName $lastName”
}
val person = Person(“John”, “Doe”)
println(person.fullName) // Output: John Doe
Use secondary constructors in a Circle class to define additional ways to create a circle using a radius or a diameter. Print the area in the init block.
class Circle(val radius: Double) {
constructor(diameter: Int) : this(diameter / 2.0) {
println(“Using diameter constructor.”)
}
init { println("Area of the circle is ${Math.PI * radius * radius}") } }
val c = Circle(4)
// Output: Area of the circle is 12.566370614359172
Create an interface Shape with a method computeArea(), and implement it in a Square class.
interface Shape {
fun computeArea(): Double
}
class Square(val side: Int) : Shape {
override fun computeArea(): Double = (side * side).toDouble()
}
val square = Square(5)
println(“Area of square: ${square.computeArea()}”) // Output: Area of square: 25.0
Constructors in Kotlin give example
class Rectangle(val length: Int, val width: Int) {
init {
println(“Area: ${length * width}”)
}
}
val rect = Rectangle(5, 3) // Output: Area: 15
Getters and Setters in Kotlin
Definition: Getters and setters allow you to retrieve and update property values. Custom versions can override default behavior.
class Person(var name: String) {
var age: Int = 0
set(value) {
field = if (value > 0) value else 0
}
}
val person = Person(“Alice”)
person.age = -5 // Negative value ignored
println(person.age) // Output: 0
Inheritance in Kotlin
open class Animal {
fun eat() = println(“Eating…”)
}
class Dog : Animal() {
fun bark() = println(“Barking…”)
}
val myDog = Dog()
myDog.eat() // Output: Eating…
myDog.bark() // Output: Barking…
Interfaces in Kotlin
An interface defines a contract that classes must follow. A class can implement multiple interfaces.
interface Drivable {
fun drive()
}
class Car : Drivable {
override fun drive() {
println(“Driving a car!”)
}
}
val car = Car()
car.drive() // Output: Driving a car!