Home » Scala language

Abstract Classes in Scala

Abstract classes are a special type of classes in Scala that are used to achieve abstraction. In this tutorial on Scala Abstract classes, we will learn about abstract classes with examples.
Submitted by Shivang Yadav, on March 06, 2020

Abstract Class

In the Scala programming language, abstraction is achieved using abstract class.

Abstraction is the process of showing only functionality and hiding the details from the final user.

Abstract classes are defined using the "abstract" keyword. An abstract class contains both abstract and non-abstract methods. Multiple inheritances are not allowed by abstract class i.e. only one abstract class can be inherited by a class.

Syntax to create Abstract Class in Scala:

abstract class class_name {
	def abstract_method () {}
	def method() {
		//code
	}
}

An abstract method is that method which does not have any function body.

Example:

abstract class bikes
{ 
	def displayDetails() 
} 

class myBike extends bikes 
{ 
	def displayDetails() 
	{ 
		println("My new bike name : Harley Davidson Iron 833 ") 
		println("Top speed : 192 kmph") 
	} 
} 

object MyObject 
{ 
	def main(args: Array[String]) 
	{ 
		var newBike = new myBike() 
		newBike.displayDetails() 
	} 
} 

Output

My new bike name : Harley Davidson Iron 833 
Top speed : 192 kmph

Some Points about Abstract Classes in Scala

  • Instance creation of Abstract class is not allowed. If we try to create objects of abstract class then an error will be thrown.
  • Field creation of an abstract class is allowed and can be used by methods of abstract class and classes that inherit it.
  • A constructor can also be created in an abstract class which will be invoked by the instance of the inherited class.



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.