Sobes.tech
Junior

What is an abstract class and what is it used for?

sobes.tech AI

Answer from AI

An abstract class is a class that contains one or more abstract (without implementation) methods or is declared with the keyword abstract, but does not contain abstract methods. It cannot be instantiated directly.

Usage:

  1. Defining common behavior: Abstract classes define a skeleton of behavior that must be implemented by its subclasses. This helps avoid code duplication.
  2. Partial implementation of an interface: Part of the interface can be implemented in an abstract class, leaving specific implementation to subclasses.
  3. Preventing instantiation: Ensures that only specific subclasses can be created.
abstract class Shape { // Abstract class
    abstract fun draw() // Abstract method

    fun fill(color: String) { // Regular method
        // Implementation of fill
    }
}

class Circle : Shape() {
    override fun draw() {
        // Implementation of circle drawing
    }
}
What is an abstract class and what is it used for… - sobes.tech