直接上代码 注意点写在注释里了
package cn.limbo.demo /** * Created by Limbo on 16/6/28. * class ClassName(),括号代表了主构造器,def this()表示定义了一个副构造器 * 类中的所有单独可执行的语句都会被包含在主构造器中 */ class Complex(val real: Int, val imaginary: Int) { def +(operand: Complex): Complex = { println("Calling + ") new Complex(real + operand.real, imaginary + operand.imaginary) } def *(operand: Complex): Complex = { println("Calling * ") new Complex(real * operand.real - imaginary * operand.imaginary, real * operand.imaginary + imaginary * operand.real) } def this(real : Int) { this(real,1) } override def toString(): String = { real + (if (imaginary < 0) "" else "+") + imaginary + "i"; } } /** * Scala继承的时候一定要在构造器中写override在父类的属性前 */ class number(override val real:Int ,override val imaginary :Int, var name: String)extends Complex(real,imaginary) { override def toString() : String = super.toString() + "name : " + name }
但是后来发现如果用var来定义属性的话是不能添加override的,原因是可变参数(var定义的参数)没有override的必要,所以若是继承,无需写var,直接写成
class Dog(name:String,age:Int )extends Pet(name, age)遇到val定义的变量再用override吧