Professional Documents
Culture Documents
(Kotlin Language)
Lab 4
Prepared By:
Eng.Marwa ELDeeb
Contact info:mmamdeeb@gmail.com
|Page1
Quick Recap
Important notes:
|Page2
abstract class Person(name: String) {
init {
println("My name is $name.") }
Output:
|Page3
interface MyInterface {
fun hello() {
println("Hello there, pal!")
}
}
println("test = ${obj.test}")
print("Calling hello(): ")
obj.hello()
Output:
test = 25
Calling hello(): Hello there, pal!
Calling and printing foo(): Lol
Kotlin does not allow true multiple inheritance. However, it's possible to
implement two or more interfaces in a single class. For example:
|Page4
interface A {
fun callMe() {
println("From interface A") }
}
interface B {
fun callMeToo() {
println("From interface B")
}
}
obj.callMe()
obj.callMeToo()
}
Output:
From interface A
From interface B
Kotlin allows you to define a class within another class known as nested
class.
you can use (.) notation to access Nested class and its members.
The nested classes in Kotlin do not have access to the outer class
instance.
you need to use inner modifier to create an inner class which we will
discuss next.
An exception is an unwanted or unexpected event, which occurs during
the execution of a program.
In Kotlin, we use try-catch block for exception handling in the program.
The try block encloses the code which is responsible for throwing an
exception and the catch block is used for handling the exception.
finally block is always executes irrespective of whether an exception is
handled or not by the catch block. So it is used to execute important code
statement.
|Page5
we use throw keyword to throw an explicit exception. It can also be used
to throw a custom exception.
// derived class
class B: A() {
fun getvalue(): Int {
// accessed from the subclass
return int
}
}
|Page6
3. what is the output?
// base class
open class A {
// protected variable
open protected val int = 10
// derived class
class B: A() {
override val int = 20
fun getvalue():Int {
// accessed from the subclass
return int
}
}
|Page7
5. what is the output?
class Animal{
// outer class property
val legs = 4
class Dog{
// nested class proprty
val leg=legs
val say = "Woof"
val hasTail = true
fun tail(){
println("Dog has tail: $hasTail")
}
}
}
fun main() {
// Creating object of nested class directly
val dog = Animal.Dog()
// Accessing inner class
dog.tail()
println("Dog says: ${dog.say}")
}
|Page8