0% found this document useful (0 votes)
4 views25 pages

03- OOP Kotlin Classes & Object

Chapter III discusses Object-Oriented Programming (OOP) in Kotlin, focusing on classes and objects. It explains the syntax for defining classes, creating objects without the 'new' keyword, and the differences between primary and secondary constructors. The chapter also covers properties, getters and setters, custom accessors, late-initialized properties, and access modifiers in Kotlin.

Uploaded by

namayheng12345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views25 pages

03- OOP Kotlin Classes & Object

Chapter III discusses Object-Oriented Programming (OOP) in Kotlin, focusing on classes and objects. It explains the syntax for defining classes, creating objects without the 'new' keyword, and the differences between primary and secondary constructors. The chapter also covers properties, getters and setters, custom accessors, late-initialized properties, and access modifiers in Kotlin.

Uploaded by

namayheng12345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Chapter III

OOP Kotlin
Classes & Object
Classes & Object
• Classes are a fundamental building block of OOP. In fact,
Kotlin classes are very similar to Java classes

• A class is like a blueprint for the objects.


Syntax:
class MyClass {
// variables or data members
// member functions
.. ..
}

2
Creating Object
• Unlike Java, Kotlin does not require the new
keyword to create a class instance:
Ex: val p = new Person();

// Instantiate Kotlin class inside Java file Person


person = new Person()
// Instantiate class inside Kotlin file
var person = Person()
3
Classes Example
class Person {
var name: String
var age: Int

constructor(name: String, age: Int) {


this.name = name
this.age = age
}
}

4
Classes Example
This is an exact equivalent of the preceding Java class:

• The constructor method is equivalent of the Java


constructor that is called when an object instance is
created.

• Getters and setters are generated by the Kotlin


compiler

5
Primary Constructor
class Person constructor(name: String, age: Int) {
var name: String
var age: Int
init {
this.name = name
this.age = age
println("Person instance created")
}
}
6
Primary Constructor
class Person constructor(name: String, age: Int) {
var name: String
var age: Int
init {
this.name = name
this.age = age
println("Person instance created")
}
}
7
Primary Constructor
In Kotlin, the primary constructor, as opposed to the secondary constructor,
can't contain any code, so all initialization code must be placed inside the
initializer block (init). An initializer block will be executed during class
creation, so we can assign constructor parameters to fields inside it.

To simplify code, we can remove the initializer block and access constructor
parameters directly in property initializers. This allows us to assign
constructor parameters to a field:
class Person constructor(name: String, age: Int) {
var name: String = name
var age: Int = age
}
8
Secondary Constructor
Kotlin may have one or more secondary constructors. Secondary
constructors allow initialization of variables and allow to provide some logic
to the class as well. They are prefixed with the constructor keyword.

class Person {
var name: String
var age: Int
constructor(name: String, age: Int) {
this.name = name
this.age = age
}
}
9
Properties
Properties in Kotlin classes can be declared either as mutable, using
the var keyword, or as read-only, using the val keyword.

class Address {
var name: String = "Holmes, Sherlock"
var street: String = "Baker"
var city: String = "London"
var state: String? = null
var zip: String = "123456"
}

10
Properties
To use a property, simply refer to it by its name:

fun copyAddress(address: Address): Address {


val result = Address() // there's no 'new' keyword in Kotlin
result.name = address.name // accessors are called
result.street = address.street
// ...
return result
}

11
Read-write versus read-only property

class Person(
var name: String,
// Read-write property (generated getter and setter)
val age: Int // Read-only property (generated getter)
)

12
Read-write versus read-only property
\\usage
val person = Person("Eva", 25)

val name = person.name


person.name = "Kate"

val age = person.age


person.age = 28 //error: read-only property

13
Getter & Setter
getters are used for getting value of the property. Similarly, setters are used
for setting value of the property.

In Kotlin, getters and setters are optional and are auto-generated if you do
not create them in your program.

The following code in Kotlin


class Person {
var name: String = "defaultValue"
}
is equivalent to
14
Getter & Setter
class Person {
var name: String = "defaultValue"

// getter
get() = field

// setter
set(value) {
field = value
}
}
15
Getter & Setter
val p = Person()
p.name = "jack“
println("${p.name}")

16
Custom Setter and Getter
Custom Getter
class Rectangle(val width: Int, val height: Int) {
val area: Int
get() = width * height // Custom getter calculates area
}

fun main() {
val rectangle = Rectangle(5, 10)
println("Area: ${rectangle.area}") // Output: Area: 50
}
17
Custom Setter and Getter
Custom Setter
class Person {
var name: String = ""
set(value) {
if (value.isNotBlank()) {
field = value // Only set if the value is not blank
} else {
println("Invalid name.")
}
}
} 18
Custom Setter and Getter
Custom Setter
fun main() {
val person = Person()
person.name = "Alice" // Sets the name because it is not blank
println("Name: ${person.name}") // Output: Name: Alice

person.name = "" // Prints "Invalid name." and does not change the name

19
Late-initialized properties
class MainActivity : AppCompatActivity() {

private lateinit var button: Button

override fun onCreate(savedInstanceState: Bundle?) {


button = findViewById(R.id.button) as Button
button.text = "Click Me"
}
}

Now, with the property marked as lateinit, we can access our application
instancewithout performing nullity checks.
20
Access Modifier in Kotlin

Note: If visibility modifier is not specified, it is public by


default.
21
Example Access Modifier
// file name: hello.kt
package test

fun function1() {} // public by default and visible everywhere

private fun function2() {} // visible inside hello.kt


internal fun function3() {} // visible inside the same module
var name = "Foo" // visible everywhere
get() = field // visible inside hello.kt (same as its property)
private set(value) { // visible inside hello.kt
field = value
}
private class class1 {} // visible inside hello.kt

22
Example Access Modifier
open class Base() {
var a = 1 // public by default
private var b = 2 // private to Base class
protected open val c = 3 // visible to the Base and the Derived class
internal val d = 4 // visible inside the same module

protected fun e() { } // visible to the Base and the Derived class
}

23
class Derived: Base() {
// a, c, d, and e() of the Base class are visible
// b is not visible

override val c = 9 // c is protected


}
fun main(args: Array<String>) {
val base = Base()
// base.a and base.d are visible
// base.b, base.c and base.e() are not visible

val derived = Derived()


// derived.c is not visible
}
24
Thank You Calligraphy Transparent PNG | PNG Mart

25

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy