CLASSES, CONSTRUCTORS, INHERITENCE CONCEPTS IN KOTLIN

PHOTO EMBED

Thu Oct 31 2024 16:15:43 GMT+0000 (Coordinated Universal Time)

Saved by @carona

1.// getter and setter properties

class CSE {
    var name: String = " "
        get() = field        // getter
        set(value) {         // setter
            field = value
        }
}
fun main(args: Array<String>) {
    val c = CSE()
    c.name = "WELCOME TO CSE-B"   // access setter
    println(c.name)               // access getter
}

Output:
WELCOME TO CSE-B



2.// object accessing

class CSE {
    fun Mobile() = println("WELCOME TO MAD LAB")
}
fun main(args: Array<String>) {     
    val obj = CSE()
    // calling Mobile() method using object obj
    obj.Mobile()
}

Output:
WELCOME TO MAD LAB

3.// companion object
class CSE {
    companion object Test  {                 //companion object name Test
        fun section_b() = println("WELCOME TO CSE-B MAD LAB")
    }
}
fun main(args: Array<String>) {
    CSE.section_b()   // method accessing using class name
}
Output:
WELCOME TO CSE-B MAD LAB


4.// accessing variable and method using class name in companion object 

class CSE
 {
    companion object Test  
   {                  //companion object name Test
        var v:Int=100
        fun section_b() = println("WELCOME TO CSE-B MAD LAB")
    }  
}
fun main(args: Array<String>) 
{
    println(CSE.v)    // accessing variable using class name
    CSE.section_b()   // method accessing using class name
}
Output:
WELCOME TO CSE-B MAD LAB


5.// creating the employee class
class employee {
	// properties / member variables
	var name: String = "XYZ"
	var age: Int = 10
	var gender: Char = 'M'
	var salary: Double = 500.toDouble()
	
	// member functions
	fun display(){
         println("WELCOME TO CSE-B")
	}
}
fun main()
{
    var obj=employee()         //object creation for class
    obj.display()              // accessing member function using object name
    // accessing properties using object name
    println(obj.name)
    println(obj.age)
    println(obj.gender)
    println(obj.salary)
    
}

Output:

WELCOME TO CSE-B
XYZ
10
M
500.0


6.//DICE ROLLER PROGRAM USING CLASSES
// Random() is an abstract class which generates random numbers with the given conditions. It can be accessed after importing Kotlin.random.Random.
//IntRange is another data type, and it represents a range of integer numbers from a starting point to an endpoint. 
//IntRange is a suitable data type for representing the possible values a dice roll can produce.
class Dice {
    var sides = 6
    fun roll(): Int {
        //random() function to generate random numbers. 
        //random() takes a series of numbers as an input and it returns a random Int as an output.
        val randomNumber = (1..sides).random()  
        return randomNumber
    }
}
fun main() {
    val myFirstDice = Dice()
    val diceRoll = myFirstDice.roll()
    println("Your ${myFirstDice.sides} sided dice rolled ${diceRoll}!")

    myFirstDice.sides = 20
    println("Your ${myFirstDice.sides} sided dice rolled ${myFirstDice.roll()}!")
}

Output:
Your 6 sided dice rolled 4!
Your 20 sided dice rolled 7!


7.// random() function
fun main() {
   // random() generates a random number between 0 to 10
   println((0..10).random())
}

Output:
7



8.//primary constructor
fun main(args: Array<String>)
{
	val add = Add(5, 6)
	println("The Sum of numbers 5 and 6 is: ${add.c}")
}
class Add constructor(a: Int,b:Int)
{
	var c = a+b;
}

Output:
The Sum of numbers 5 and 6 is 11



9.//secondary constructor
fun main(args: Array<String>)
{
	Add(5, 6)
}
//class with one secondary constructor
class Add
{
	constructor(a: Int, b:Int)
	{
		var c = a + b
		println("The sum of numbers 5 and 6 is: ${c}")
	}
}


Output:
The Sum of numbers 5 and 6 is 11

10.//this keyword and  Constructor Declaration of Class
//Kotlin program of creating multiple objects and accessing the property and member function of class:
class employee {
	var name: String = ""
	var age: Int = 0
	var gender: Char = 'M'
	var salary: Double = 0.toDouble()

	fun insertValues(n: String, a: Int, g: Char, s: Double) {
		name = n
		age = a
		gender = g
		salary = s
		println("Name of the employee: $name")
		println("Age of the employee: $age")
		println("Gender: $gender")
		println("Salary of the employee: $salary")
	}
	
	fun insertName(n: String) {
		this.name = n
	}

}
fun main(args: Array<String>) {
	// creating multiple objects
	var obj = employee()
	
	// object 2 of class employee
	var obj2 = employee()

	//accessing the member function
	obj.insertValues("X1", 50, 'M', 500000.00)

	// accessing the member function
	obj2.insertName("X2")

	// accessing the name property of class
	println("Name of the new employee: ${obj2.name}")

}


Output:

Name of the employee: X1
Age of the employee: 50
Gender: M
Salary of the employee: 500000.0
Name of the new employee: X2




11.//INHERITENCE IN KOTLIN
//base class
open class baseClass{
	val name = "CSE-B"
	fun A(){
		println("Base Class")
	}
}
//derived class
class derivedClass: baseClass() {
	fun B() {
		println(name)		 //inherit name property
		println("Derived class")
	}
}
fun main(args: Array<String>) {
	val obj = derivedClass()
	obj.A()		 // inheriting the base class function
	obj.B()		 // calling derived class function
}


Output:

Base Class
CSE-B
Derived class




12. //DWELLINGS PROGRAM
 /**
* Program that implements classes for different kinds of dwellings.
* Shows how to:
* Create class hierarchy, variables and functions with inheritance,
* abstract class, overriding, and private vs. public variables.
*/

import kotlin.math.PI
import kotlin.math.sqrt

fun main() {
   val squareCabin = SquareCabin(6, 50.0)
   val roundHut = RoundHut(3, 10.0)
   val roundTower = RoundTower(4, 15.5)

   with(squareCabin) {
       println("\nSquare Cabin\n============")
       println("Capacity: ${capacity}")
       println("Material: ${buildingMaterial}")
       println("Floor area: ${floorArea()}")
   }

   with(roundHut) {
       println("\nRound Hut\n=========")
       println("Material: ${buildingMaterial}")
       println("Capacity: ${capacity}")
       println("Floor area: ${floorArea()}")
       println("Has room? ${hasRoom()}")
       getRoom()
       println("Has room? ${hasRoom()}")
       getRoom()
       println("Carpet size: ${calculateMaxCarpetLength()}")
   }

   with(roundTower) {
       println("\nRound Tower\n==========")
       println("Material: ${buildingMaterial}")
       println("Capacity: ${capacity}")
       println("Floor area: ${floorArea()}")
       println("Carpet Length: ${calculateMaxCarpetLength()}")
   }
}


/**
* Defines properties common to all dwellings.
* All dwellings have floorspace,
* but its calculation is specific to the subclass.
* Checking and getting a room are implemented here
* because they are the same for all Dwelling subclasses.
*
* @param residents Current number of residents
*/
abstract class Dwelling(private var residents: Int) {
   abstract val buildingMaterial: String
   abstract val capacity: Int

   /**
    * Calculates the floor area of the dwelling.
    * Implemented by subclasses where shape is determined.
    *
    * @return floor area
    */
   abstract fun floorArea(): Double

   /**
    * Checks whether there is room for another resident.
    *
    * @return true if room available, false otherwise
    */
   fun hasRoom(): Boolean {
       return residents < capacity
   }

   /**
    * Compares the capacity to the number of residents and
    * if capacity is larger than number of residents,
    * add resident by increasing the number of residents.
    * Print the result.
    */
   fun getRoom() {
       if (capacity > residents) {
           residents++
           println("You got a room!")
       } else {
           println("Sorry, at capacity and no rooms left.")
       }
   }

   }

/**
* A square cabin dwelling.
*
*  @param residents Current number of residents
*  @param length Length
*/
class SquareCabin(residents: Int, val length: Double) : Dwelling(residents) {
   override val buildingMaterial = "Wood"
   override val capacity = 6

   /**
    * Calculates floor area for a square dwelling.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return length * length
   }

}

/**
* Dwelling with a circular floorspace
*
* @param residents Current number of residents
* @param radius Radius
*/
open class RoundHut(
       residents: Int, val radius: Double) : Dwelling(residents) {

   override val buildingMaterial = "Straw"
   override val capacity = 4

   /**
    * Calculates floor area for a round dwelling.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return PI * radius * radius
   }

   /**
    *  Calculates the max length for a square carpet
    *  that fits the circular floor.
    *
    * @return length of square carpet
    */
    fun calculateMaxCarpetLength(): Double {
        return sqrt(2.0) * radius
    }
}

/**
* Round tower with multiple stories.
*
* @param residents Current number of residents
* @param radius Radius
* @param floors Number of stories
*/
class RoundTower(
       residents: Int,
       radius: Double,
       val floors: Int = 2) : RoundHut(residents, radius) {

   override val buildingMaterial = "Stone"

   // Capacity depends on the number of floors.
   override val capacity = floors * 4

   /**
    * Calculates the total floor area for a tower dwelling
    * with multiple stories.
    *
    * @return floor area
    */
   override fun floorArea(): Double {
       return super.floorArea() * floors
   }
}

Output:
Square Cabin
============
Capacity: 6
Material: Wood
Floor area: 2500.0

Round Hut
=========
Material: Straw
Capacity: 4
Floor area: 314.1592653589793
Has room? true
You got a room!
Has room? false
Sorry, at capacity and no rooms left.
Carpet size: 14.142135623730951

Round Tower
==========
Material: Stone
Capacity: 8
Floor area: 1509.5352700498956
Carpet Length: 21.920310216782976





13.//repeat  statement
fun main(args: Array<String>) {
    repeat(4) {
        println("WELCOME TO CSE-B!")
    }
}


Output:

WELCOME TO CSE-B!
WELCOME TO CSE-B!
WELCOME TO CSE-B!
WELCOME TO CSE-B!




14. // INIT BLOCK
class InitOrderDemo(name: String) {
    val firstProperty = "First property: $name".also(::println)
    
    init {
        println("First initializer block that prints $name")
}
  val secondProperty = "Second property:${name.length}".also(::println)
    
    init {
        println("Second initializer block that prints ${name.length}")
    }
}

fun main() {
    InitOrderDemo("hello")
}

Output:
First property: hello
First initializer block that prints hello
Second property: 5
Second initializer block that prints 5

15.//RANGETO() function
fun main(args : Array<String>){

	println("Integer range:")
	// creating integer range
	for(num in 1.rangeTo(5)){
		println(num)
	}
}

Output:
Integer range:
1
2
3
4
5




16. //downTo() function

fun main(args : Array<String>){

	println("Integer range in descending order:")
	// creating integer range
	for(num in 5.downTo(1)){
		println(num)
	}
}
Output:

Integer range in descending order:
5
4
3
2
1


17. //step keyword

fun main(args: Array<String>) {
	//for iterating over the range
	var i = 2
	// for loop with step keyword
	for (i in 3..10 step 2)
		print("$i ")
	println()
	// print first value of the range
	println((11..20 step 2).first)
	// print last value of the range
	println((11..20 step 4).last)
	// print the step used in the range
	println((11..20 step 5).step)
}

Output:

3 5 7 9 
11
19
5



18. //reversed function
fun main(args: Array<String>) {
	var range = 2..8
	for (x in range.reversed()){
		print("$x ")
	}
}

Output:
8 7 6 5 4 3 2 





19. //In Operator Example Program in Kotlin
 fun main(args: Array<String>) {
    val collection = 10..20
    val num2 = 5

    println("in operator in if condition")
    if (15 in collection) {
        println("15 is in $collection")
    }

    println("\nin operator in for loop")
    for(item in collection){
        println("$item is in $collection")
    }

    println("\nin operator in when statement")
    when{
        19 in collection -> println("19 in collection is true")
    }
}


Output:
in operator in if condition
15 is in 10..20

in operator in for loop
10 is in 10..20
11 is in 10..20
12 is in 10..20
13 is in 10..20
14 is in 10..20
15 is in 10..20
16 is in 10..20
17 is in 10..20
18 is in 10..20
19 is in 10..20
20 is in 10..20

in operator in when statement
19 in collection is true
content_copyCOPY