Inheritance



// File:            Main.kt
// Programmer: Engineer Nolverto Urias Obeso
// Creation Date: 06/18/2023
// Email: nolvertou@gmail.com
// Description: Learn how to use the inheritance

fun main() {
buildTowerTank()
}

fun buildTowerTank() {
val smallAquarium = Aquarium()
println("Small Aquarium: ${smallAquarium.volume} liters (Max Capacity) with " +
"Length: ${smallAquarium.length} cm, " +
"Width: ${smallAquarium.width} cm, " +
"Height: ${smallAquarium.height} cm, " +
"Water: ${smallAquarium.water} liters")

val towerTank = TowerTank()
println("TowerTank: ${towerTank.volume} liters (Max Capacity) with " +
"Length: ${towerTank.length} cm, " +
"Width: ${towerTank.width} cm, " +
"Height: ${towerTank.height} cm, " +
"Water: ${towerTank.water} liters")
}
Parent Class:

// To inherit from a class you have to change the class to open, by default classes are not subclassible and we have to
// explicitly allow it using open keyword on the left hand of class keyword
open class Aquarium(var length: Int = 100, var width: Int = 20, var height: Int = 40) { // Primary Constructor
// We must add the open keyword to override the attribute value using inheritance
open var volume: Int
get() = width * height * length / 1000 // It calculates the volume
set(value){ height = (value * 1000) / (width * length)} // It sets the height giving the volume value

// We must add the open keyword to override the attribute value using inheritance
open var water = volume * 0.9 // It's used the 90% of the tank volume


// The arguments have to match exactly the with one of the available constructors
// If you declare a secondary constructor it must containt a call to the primary constructor by using this()
constructor(numberOfFish:Int): this(){ // Secondary constructor
val water:Int = numberOfFish * 2000 //cm3
val tank: Double = water + water * 0.1
height = (tank/(length*width)).toInt() // Calculates the height depending of number of fish
}

}
Child Class:
import kotlin.math.PI

class TowerTank() : Aquarium() {
// If we want to change the inherited attributes we must use override keyword and add open keyword to the parent attribute
override var water = volume *0.8

override var volume: Int
get() = (width * height * length / (1000 * PI)).toInt()
set(value) {height = (value * 1000) / (width * length)}
}

Comments

Popular posts from this blog