在定义类的继承关系时,有时你不希望基类的某些成员被子类重载,和Java类似,在Scala中也是使用final来修饰类的成员。比如在前面的ArrayElement例子,在demo方法前加上final修饰符,
- class ArrayElement extends Element {
- final override def demo() {
- println("ArrayElement's implementation invoked")
- }
- }
如果LineElement试图重载demo,则会报错:
- scala> class LineElement extends ArrayElement {
- | override def demo() {
- | println("LineElement's implementation invoked")
- | }
- |
- | }
- <console>:10: error: overriding method demo in class ArrayElement of type ()Unit;
- method demo cannot override final member
- override def demo() {
如果你希望某个类不可以派生子类,则可以在类定义前加上final修饰符:
- final class ArrayElement extends Element {
- override def demo() {
- println("ArrayElement's implementation invoked")
- }
- }
此时如果还是重载LineElement的demo函数,则会报错:
- scala> class LineElement extends ArrayElement {
- | override def demo() {
- | println("LineElement's implementation invoked")
- | }
- |
- | }
- <console>:9: error: illegal inheritance from final class ArrayElement
- class LineElement extends ArrayElement {