scala抽象类如何实现
在Scala中,可以使用关键字abstract来定义抽象类。抽象类是不能被实例化的,只能被继承。
下面是一个简单的例子:
abstract class Animal {
def sound(): Unit
}
class Dog extends Animal {
override def sound(): Unit = {
println("汪汪汪")
}
}
class Cat extends Animal {
override def sound(): Unit = {
println("喵喵喵")
}
}
object Main extends App {
val dog = new Dog()
dog.sound() // 输出:汪汪汪
val cat = new Cat()
cat.sound() // 输出:喵喵喵
}
在上面的例子中,定义了一个抽象类Animal,其中包含一个抽象方法sound()。然后通过两个具体的子类Dog和Cat来实现这个抽象方法。
注意,由于抽象类不能被实例化,所以在Main对象中创建了Dog和Cat的实例来调用sound()方法
原文地址: http://www.cveoy.top/t/topic/hMpw 著作权归作者所有。请勿转载和采集!