CH 3 - Classes and objects Flashcards

1
Q

what is a class

A

A class in Kotlin is a blueprint for creating objects. It defines the properties (data) and methods (behaviors) that its object instances will have.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the difference between a class and an object instance in Kotlin?

A

A class is the blueprint, while an object instance is a specific realization of that class with actual values for its properties.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Explain the purpose of a constructor in Kotlin.

A

constructor initializes an object when it is created. Kotlin classes can have primary constructors (defined in the class header) and secondary constructors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the role of the init block in Kotlin classes?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can you make a Kotlin class subclassable?

A

sue the open keyword to allow subclassing, as Kotlin classes are final by default.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a data class, and what features does it provide automatically?

A

A data class is a special class used to store data. It automatically generates methods like toString(), equals(), hashCode(), and copy().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

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.

A

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()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

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.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Write a Kotlin class Person with properties firstName and lastName. Use a custom getter for a fullName property that combines firstName and lastName.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

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.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Create an interface Shape with a method computeArea(), and implement it in a Square class.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Constructors in Kotlin give example

A

class Rectangle(val length: Int, val width: Int) {
init {
println(“Area: ${length * width}”)
}
}

val rect = Rectangle(5, 3) // Output: Area: 15

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Getters and Setters in Kotlin

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Inheritance in Kotlin

A

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…

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Interfaces in Kotlin

A

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!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Extension Functions

A

Extension functions allow you to add functionality to existing classes without modifying them.

fun String.isLongerThanFive() = this.length > 5

println(“Hello”.isLongerThanFive()) // Output: false
println(“Kotlin”.isLongerThanFive()) // Output: true

17
Q

Data Classes

A

Data classes are used to store data and automatically generate toString(), equals(), hashCode(), and copy() methods.

data class Player(val name: String, val score: Int)

val player = Player(“Alice”, 100)
println(player) // Output: Player(name=Alice, score=100)

18
Q

Enum Classes

A

num classes define a set of constants that represent specific values.

enum class Direction {
NORTH, SOUTH, EAST, WEST
}

val dir = Direction.NORTH
println(dir) // Output: NORTH

19
Q

Singletons (Object Keyword)

A

The object keyword defines a singleton class, meaning only one instance of the class exists.

object Logger {
fun log(message: String) = println(“Log: $message”)
}

Logger.log(“Singleton example”) // Output: Log: Singleton example

20
Q

Companion Objects

A

A companion object allows sharing static-like members (variables or methods) across all instances of a class.

class MathOperations {
companion object {
fun add(a: Int, b: Int) = a + b
}
}

println(MathOperations.add(5, 3)) // Output: 8

21
Q

Packages

A

Packages in Kotlin help organize code by grouping related classes and functions.

package com.example.myapp

class MyClass {
fun greet() = println(“Hello from MyClass!”)
}

22
Q

Visibility Modifiers

A

isibility modifiers control access to classes, methods, and properties (public, private, protected).

class Person {
private var name: String = “Unknown”

fun setName(newName: String) {
    name = newName
}

fun getName() = name }

val person = Person()
person.setName(“Alice”)
println(person.getName()) // Output: Alice