标签:
1 类
(1)
scala把主构造函数放到类的定义中,让定义字段及相应方法变得简单起来。
class People(age: Int, name: String)
scala会自动将这个类变成public,默认的就是public. 如果我们将age这个字段设为 val age: Int,则scala将其定义成为一个private final 字段,并为它创建一个public方法number() 用以取值。如果var name: String,则定义name为private字段,并同时提供public的getter和setter方法。如果不做修饰,则设定为private的getter和setter方法。
class People{ println("Hello") }
当new People时会显示输出结果:Hello
除了主构造函数,还可以通过this()副方法构造
class People(age: Int, name: String){ private var address: String = _ def this(age: Int, name: String, add: String){ this(age,name) address = add } }
(2) 单例
单例实例对象无法初始化,所以不能给它的主构造函数传递参数
object test{ def calSum(start_index:Int, end_index:Int, call_fun: Int => Int) = { var result = 0 for (i <- start_index to end_index){ result += call_fun(i) } result } def main(args: Array[String]){ if (args.length > 0) { for (line <- Source.fromFile(args(0)).getLines) println(line.length + " " + line) } else Console.err.println("Please enter filename") } }
(3)继承
两点需要注意a) 重写父类方法需要显示override关键字,b)只有主构造函数才能往基类构造函数中传递参数
class People(age: Int, name: String){ override def toString() = { "age: "+age + " name: "+name } } class Man(age: Int, name: String, sex: String) extends People(age,name){ override def toString() = { "age: "+age + " name: "+name + " sex: "+sex } }
简单点
class People(age: Int, name: String){ override def toString = "age: "+age + " name: "+name } class Man(age: Int, name: String, sex: String) extends People(age,name){ override def toString = "age: "+age + " name: "+name + " sex: "+sex }
标签:
原文地址:http://www.cnblogs.com/yxzfscg/p/4907472.html