📜  Scala中特征和抽象类的区别

📅  最后修改于: 2022-05-13 01:54:19.488000             🧑  作者: Mango

Scala中特征和抽象类的区别

在 Scala 中,抽象类是使用 abstract 关键字构造的。它包含抽象和非抽象方法,不能支持多重继承。
例子:

// Scala program to illustrate how to 
// create an abstract class
  
// Abstract class
abstract class Abstclass
{
      
    // Abstract and non-abstract method
    def portal
    def tutorial()
    { 
        println("Scala tutorial")
    }
  
}
  
// GFG class extends abstract class
class GFG extends Abstclass
{
    def portal()
    {
        println("Welcome!! GeeksforGeeks")
    }
}
  
object Main 
{
      
    // Main method
    def main(args: Array[String]) 
    {
        // object of GFG class
        var obj = new GFG ();
        obj.tutorial()
        obj.portal()
    }
}

输出:

Scala tutorial
Welcome!! GeeksforGeeks

与类一样, Traits可以有方法(抽象和非抽象)和字段作为其成员。 Traits 就像Java中的接口。但是它们比Java中的接口更强大,因为在特性中我们可以实现成员。
例子:

// Scala program to illustrate how to 
// create traits
  
// traits
trait mytrait
{
      
    // Abstract and non-abstract method
    def portal
    def tutorial()
    { 
        println("Scala tutorial")
    }
  
}
  
// GFG class extends trait
class GFG extends mytrait
{
    def portal()
    {
        println("Welcome!! GeeksforGeeks")
    }
}
  
object Main 
{
      
    // Main method
    def main(args: Array[String]) 
    {
          
        // object of GFG class
        var obj = new GFG ();
        obj.tutorial()
        obj.portal()
    }
}

输出:

Scala tutorial
Welcome!! GeeksforGeeks
TraitsAbstract Class
Traits support multiple inheritance.Abstract class does not support multiple inheritance.
We are allowed to add a trait to an object instance.We are not allowed to add an abstract class to an object instance.
Traits does not contain constructor parameters.Abstract class contain constructor parameters.
Traits are completely interoperable only when they do not contain any implementation code.Abstract class are completely interoperable with Java code.
Traits are stackable. So, super calls are dynamically bound.Abstract class is not stackable. So, super calls are statically bound.