前面我们了解了类和对象,本节我们将了解scala当中的抽象类、扩展类以及特质【相当于java中的接口】。
abstract class AbstractUserService {
val name:String
val age = 10;
def test;
def test(age:Int);
def test(salary:Float): Unit ={
println(salary);
}
}
class UserService extends AbstractUserService {
override val name: String = "ali";
override def test: Unit = {
println(name)
}
override def test(age: Int): Unit = {
println(name+" "+age)
}
override def test(salary: Float): Unit = {
println(name+" "+salary)
}
}
object Test {
def main(array:Array[String]): Unit ={
val abstractUserService = new UserService
abstractUserService.test(10)
abstractUserService.test(123.5f)
abstractUserService.test
}
}
//定义一个特质
trait Jumpable {
//抽象变量,即没有赋值
var maxHeight:Float
//定义一个方法,没有参数的情况下可以不用加括号
def jump;
def info(): Unit ={
println("it is a jumpable animal");
}
}
//重新实现该特质
class JumpImpl extends Jumpable {
override var maxHeight: Float = 1.5f
override def jump: Unit = {
print("jump")
}
}
//测试
object TestJump {
def main(array:Array[String]): Unit ={
val jumpable = new JumpImpl
jumpable.jump;
jumpable.info();
}
}
以上就是scala当中的抽象类、扩展类以及特质。
原文:https://www.cnblogs.com/alichengxuyuan/p/12576844.html