天天看点

scala中抽象类和特质_Scala中特质与抽象类的区别

scala中抽象类和特质

Scala中的抽象类 (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.

Scala中的Abstract类是使用abstract关键字创建的。 抽象类中包含抽象方法和非抽象方法。

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
           

Scala的特质 (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.

Scala中的特征是使用trait关键字创建的。 特性包含抽象和非抽象的方法和字段。 这些类似于Java中的接口。 它们还允许多重继承,并且与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.
特质 抽象类
允许多个继承。 不允许多重继承。
特性中不允许使用构造函数参数。 抽象类中允许使用构造函数参数。
特质代码在实施之前是可以互操作的。 抽象类的代码是完全可互操作的。
可以将特性添加到Scala中的对象实例。 无法将抽象类添加到Scala中的对象实例。
翻译自: https://www.includehelp.com/scala/difference-between-traits-and-abstract-class.aspx

scala中抽象类和特质