转:scala override的学习总结
程序员文章站
2024-01-18 11:55:40
...
1) 可以用override val 覆盖父类或trait中不带参数的def , 但反过来不行, 既不可以用override def 覆盖父类的val,比如
class Father{
def name = "Archer"
def score() = 1.0
val id = 12
}
class Children extends Father{
override val name = "Jack"
override val score = 2.0
override def id = 10 // error: error overriding value id in class Father of type Int; method id is not stable
}
个人认为这条规则可以这么记忆,因为def表示一个函数,函数返回值都有一个确定的范围,比如上面的name函数,它的返回值范围是全体的字符串,由于val 表示一个常量,值的范围已经却确定,因此如果子类要覆盖父类的同名成员,其值的范围不能更宽泛, 否则就破坏了里氏代换原则。显然, def 所蕴含的范围要比 val 广(注: 这段话是我瞎说,只是方便记忆)
2. 子类的def 可以 override 父类的def, 比如
class Father{
def name = "Archer"
def say() = "go to bed"
def moveTo(x: Int, y: Int) = println("move to ("+x+","+y);
}
class Children extends Father{
override def name() = "Jack"
override def say() = "I'm not tired"
override moveTo(x: Int, y: Int) = super.moveTo(x,y)
}
3. 子类的var要override 父类的def 成员 , 不过def 必须成对出现;但反过来不行
class Father{
def credit = "abc"
def credit_=(s: String) = (println("s"))
}
class Children extends Father{
override var credit = "fff" // var can override a dual def
}
class Father{
def name = "Archer"
def score() = 1.0
val id = 12
}
class Children extends Father{
override val name = "Jack"
override val score = 2.0
override def id = 10 // error: error overriding value id in class Father of type Int; method id is not stable
}
个人认为这条规则可以这么记忆,因为def表示一个函数,函数返回值都有一个确定的范围,比如上面的name函数,它的返回值范围是全体的字符串,由于val 表示一个常量,值的范围已经却确定,因此如果子类要覆盖父类的同名成员,其值的范围不能更宽泛, 否则就破坏了里氏代换原则。显然, def 所蕴含的范围要比 val 广(注: 这段话是我瞎说,只是方便记忆)
2. 子类的def 可以 override 父类的def, 比如
class Father{
def name = "Archer"
def say() = "go to bed"
def moveTo(x: Int, y: Int) = println("move to ("+x+","+y);
}
class Children extends Father{
override def name() = "Jack"
override def say() = "I'm not tired"
override moveTo(x: Int, y: Int) = super.moveTo(x,y)
}
3. 子类的var要override 父类的def 成员 , 不过def 必须成对出现;但反过来不行
class Father{
def credit = "abc"
def credit_=(s: String) = (println("s"))
}
class Children extends Father{
override var credit = "fff" // var can override a dual def
}
上一篇: 怎么把cookie自动填进表单啊?