liveBook · Manning

Abstract member

As explained in Kotlin in Action, 2E

An abstract method is a method declaration without an implementation that must be implemented by a concrete implementing class.

An abstract member declares required behavior without providing an implementation. A concrete class must override it before it can be used as an implementation. section 4.1.1 section 4.1.2

Abstract members in an abstract class

abstract class Animated { abstract val animationSpeed: Double val keyframes: Int = 20 open val frames: Int = 60 abstract fun animate() open fun stopAnimating() { /* ... */ } fun animateTwice() { /* ... */ } } Here, animationSpeed and animate have no implementations and must be overridden. keyframes and animateTwice are ready to use, while frames and stopAnimating may be overridden. section 4.1.2

Use abstract members with these Kotlin rules:

  • Declare an abstract class when its members describe incomplete behavior that only a subclass can make concrete. section 4.1.2
  • Leave the body out of an interface method to require every non-abstract implementation to provide it; a method with a body supplies default behavior instead. section 4.1.1
  • Mark implementations with override; unlike Java's optional @Override annotation, Kotlin requires the modifier. section 4.1.1
  • Treat abstract members as open automatically; interfaces likewise make members open, and interface members without bodies are abstract without requiring the keyword. section 4.1.2
Listing 4.11 Declaring an abstract class
abstract class Animated {                     #1
    abstract val animationSpeed: Double       #2
    val keyframes: Int = 20                   #3
    open val frames: Int = 60                 #3
 
    abstract fun animate()                    #4
    open fun stopAnimating() { /* ... */ }    #5
    fun animateTwice() { /* ... */ }          #5
}

Inspect the complete abstract-class example, including abstract properties, abstract methods, implemented members, and overridable members. section 4.1.2

How Kotlin in Action, 2E covers it

How deep it goes
Explains declarations, implementation requirements, implicit openness, and contrasts abstract members with open and implemented members.
Examples
Uses a Clickable interface and an Animated abstract class with abstract properties and methods.
What it assumes
Assumes familiarity with Kotlin classes and inheritance while distinguishing interfaces, abstract classes, and overriding.
What you can do after
Build it from scratch by declaring abstract contracts and implementing them in concrete classes.
How it connects
Connects abstract members with interfaces, abstract classes, inheritance, overriding, and open and final modifiers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.