Q:

Kotlin program | Example of abstract class

belongs to collection: Kotlin Class and Object Programs

0

Abstract Class

  • Use the abstract keyword to mark the class as an abstract class.
  • An abstract class can't be Instantiated.but they can be subclassed.
  • An abstract class is by default inheritable not need to mark with 'open'.
  • Abstract members( (properties and function ) is by default 'open'
  • Members (properties and function ) of an abstract class can be abstract or non-abstract, to mark them abstract explicitly use abstract keyword
  • An abstract member does not have an implementation in its class.
  • If any members of the class is abstract then the class must be declared as abstract class.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program for abstract class in Kotlin

package com.includehelp

//Declare abstract class
abstract class PaintSheet {
    //abstract property without value
    abstract var value:Int

    //Init Block of Base Class
    init {
        println("Init Block, Base Class")
    }

    //marked function with 'open' to make overridable
    open fun paint(){
        println("Paint Method , Base Class Implementation")
    }

    //final method, so cant be override in subclass
    fun sketch(){
        println("Sketch Method , From Base Class!")
    }

    //Abstract method, without implementation
    abstract fun draw()
}

//declare sub class extendign super class
class Painting : PaintSheet() {

    //override abstract property in subclass
    override var value=10

    //Init Block , Sub class
    init {
        println("Init Block, Child Class")

        //Call Super class implementation of Paint method
        super.paint()
    }

    //implement base class abstract method
    override fun draw(){
        println("draw Method , override in Child Class")
    }

    //Override method, provide different implementation
    override fun paint(){
        println("Paint Method , Child Class Implementation")
    }

    //Declare Method to print Property value
    fun printValue(){
        println("Value : $value")
    }
}

//Main Function, Entry Point of Program
fun main(args:Array<String>){
    //create instance of Painting class (Child class)
    val paint = Painting()

    //call draw method
    paint.draw()

    //call paint method
    paint.paint()

    //call sketch method
    paint.sketch()

    //Call printValue method
    paint.printValue()
}

Output:

Init Block, Base Class
Init Block, Child Class
Paint Method , Base Class Implementation
draw Method , override in Child Class
Paint Method , Child Class Implementation
Sketch Method , From Base Class!
Value : 10

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Kotlin program | Companion object features... >>
<< Kotlin program | Example of Various Visibility Mod...