Classes Flashcards

1
Q

What is a sealed class?

A
All subclasses of a sealed class must be defined in the same file as the sealed class.
All subclasses are therefore known at compile time (similar to enums)
A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are kotlin’s 3 uses of the object keyword?

A
object declaration - defines a Singleton class
object Singleton { }
companion object - a nested class defining 'static' members related to the outer class
companion object { }
object expression (anonymous object) - Creates an instance of the object on the fly, the same as Java's anonymous inner classes
Thread (object : Runnable {
    override fun run( ) {
        println("I'm created with anonymous object")
    }
} ).run( )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between enum constants and subclasses of a sealed class?

A

Each enum constant exists only as a single instance, whereas a subclass of a sealed class can have multiple instances, each with its own state.

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

What is the effect of placing val in front of a parameter being passed into a constructor?

A
The property is declared AND initialised when the constructor is called.
It is therefore available to class members without having to be initialised within the class body.
class Foo(val bar: Bar) {
is the same as
class Foo(bar:Bar){
val bar = bar
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is a data class?

A
A class whose main purpose is to hold data.
Utility functions are mechanically derivable (eg equals(); toString())
The rules for creating a data class are stricter (eg at least one param in constructor)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the four visibility modifiers and their purposes?

A
public - visible everywhere
private - visible inside the same class only
internal - visible inside the same module
protected - visible inside the same class and its subclasses
How well did you know this?
1
Not at all
2
3
4
5
Perfectly