Home » Scala language

Difference between Traits and Abstract Class in Scala

Traits vs Abstract Class: Abstract class and trait both are important parts of object-oriented programming. In this tutorial, we will understand the difference between traits and abstract classes in Scala.
Submitted by Shivang Yadav, on March 06, 2020

Abstract Class in Scala

Abstract Class in Scala is created using the abstract keyword. Both abstract and non-abstract methods are included in an abstract class.

Multiple inheritances are not supported by them.

Syntax:

abstract class class_name{
	def abstract_mathod
	def general_method(){
	}
}

Example:

abstract class bike 
{ 
	def speed  
	def display() 
	{
		println("This is my new Bike") ;
	}
} 

class ninja400 extends bike 
{ 
	def speed() 
	{ 
		println("Top Speed is 178 Kmph"); 
	} 
} 

object myObject 
{ 
	def main(args: Array[String]) 
	{ 
		var obj = new ninja400(); 
		obj.display() ;
		obj.speed() ;
	} 
} 

Output

This is my new Bike
Top Speed is 178 Kmph

Traits in Scala

Traits in Scala are created using trait keyword. Traits contain both abstract and non-abstract methods and fields. These are similar to interfaces in java. They allow multiple inheritances also and they are more powerful as compared to their successors in java.

Syntax:

trait trait_name{
}

Example:

trait bike 
{ 
	def speed  
	def display() 
	{ 
		println("This is my new Bike") ;
	} 
} 

class ninja400 extends bike 
{ 
	def speed() 
	{ 
		println("Top Speed is 178 Kmph"); 
	} 
} 

object myObject 
{ 
	def main(args: Array[String]) 
	{ 
		var obj = new ninja400(); 
		obj.display() ;
		obj.speed() ;
	} 
} 

Output

This is my new Bike
Top Speed is 178 Kmph

Difference between abstract class and traits

Traits Abstract Class
Allow multiple inheritances. Do not Allow multiple inheritances.
Constructor parameters are not allowed in Trait. Constructor parameter are allowed in Abstract Class.
The Code of traits is interoperable until it is implemented. The code of abstract class is fully interoperable.
Traits can be added to an object instance in Scala. Abstract classes cannot be added to object instance in Scala.


Comments and Discussions!

Load comments ↻





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