Scala Abstract Class

A class which is declared with abstract keyword is known as abstract class. An abstract class can have abstract methods and non-abstract methods as well. Abstract class is used to achieve abstraction. Abstraction is a process in which we hide complex implementation details and show only functionality to the user.

In scala, we can achieve abstraction by using abstract class and trait. We have discussed about these in detail here.


Scala Abstract Class Example

In this example, we have created a Bike abstract class. It contains an abstract method. A class Hero extends it and provides implementation of its run method.

A class that extends an abstract class must provide implementation of its all abstract methods. You can't create object of an abstract class.

Output:

running fine...

Scala Abstract Class Example: Having Constructor, Variables and Abstract Methods

Output:

Running fine...
a = 10
b = 20
c = 30
Performance awesome

Scala Abstract Class Example: Abstract Method is not implemented

In this example, we didn't implement abstract method run(). Compiler reports an error during compilation of this program. Error message is given below in output section.

Output:

error: class Hero needs to be abstract, since method run in class Bike of type ()Unit is not defined
class Hero extends Bike{
      ^
one error found

To avoid this problem either you must implement all abstract members of abstract class or make your class abstract too.

Next TopicScala Trait




Contact US

Email:[email protected]

Scala Abstract Class
10/30