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:
Syntax
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
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()
}
Login to try C/C++/Java/PHP code in the editor
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
- Creating an instance with
new Shape(), which fails because an abstract class cannot be instantiated. - Forgetting to implement an abstract method in a subclass, so the subclass must be declared
abstracttoo. - Writing
overridewhen 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: