← Back to Scala Course | Chapter 8: Inheritance & Traits | Lesson 3 of 7

Abstract Classes

An abstract class is a half-drawn plan that nobody can build from as is. It leaves some parts for the classes that extend it to complete.

In this page:

  1. Abstract Classes
Syntax
scala
abstract class ClassName {
  def abstractMethod(param: Type): ReturnType    // no body
  def concreteMethod(): ReturnType = expression
}

class Child extends ClassName {
  def abstractMethod(param: Type): ReturnType = expression
}

Abstract Classes

An abstract class cannot be instantiated directly and may declare abstract members (methods or fields with no implementation) that subclasses are required to provide.

Abstract classes can still hold constructor parameters and concrete (fully-implemented) methods alongside abstract ones. A class can extend at most one abstract class, the same single-inheritance rule as regular classes.

Warning: Trying to write new Shape() on an abstract Shape class is a compile error.

Example: Abstract Classes

markup
abstract class Shape {
  def area(): Double

  def describe(): Unit = {
    println(s"Area is ${area()}")
  }
}

class Square(side: Double) extends Shape {
  def area(): Double = side * side
}

object Main extends App {
  val sq = new Square(4)
  sq.describe()
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Creating an instance with new Shape(), which fails because an abstract class cannot be instantiated.
  2. Forgetting to implement an abstract method in a subclass, so the subclass must be declared abstract too.
  3. Writing override when implementing an abstract method, which is optional, but forgetting a needed method causes an error.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.