(1)类,对象

  • //定义类(属性、方法),实例化对象
class counter{                                                                        *//主构造器  class counter(name:String,mode:Int){ ... }  实例化:val mycoun = new counter("mycoun",3)
private var privatevalue = 0
private var name = " "
private var mode = 1
def value = privatevalue
def value_ = (newvalue:Int){
if(newvalue >0) privatevalue = newvalue
} *//value、value_方法定义了getter,setter
def this(name:String){
this()
this.name = name
} *//第一个辅助构造器(用于实例化时参数的个数)
def this(name:String,mode:Int){
this(name)
this.mode = mode
} *//第二个辅助构造器 def increment(step:Int): Unit = {value+=step} *//函数参数step
def current(): Int = { value}
}
object Mycounter{ * //声明放在对象中进行编译 (不编译运行不用放入)
def main (args:Array[String]){
val mycounter = new counter() //实例化对象 val coun1 = new counter("coun1") * //第一个辅助构造器实例化
val coun2 = new counter("coun2",2) * //第二个辅助构造器实例化
print(mycounter.value) //getter
mycounter.value = 3 //setter
mycouter.increment(1) // 调用函数
println(mycounter.currrent())
}

文件名Test.scala

运行:scalac Test.scala // 编译

scala -classpath .Mycounter

单例对象:(类似java静态方法)

class person{                                                                            *//编译后类, 里面的成员变为实例成员
private var id = person.newpersonid() *//类和它的伴生对象的私有字段和方法可以相互调用(必须存在于同一个文件中)
private var name = " "
def this(name:String){
this()
this.name = name
}
def info() {
println(id,name)
}
}
object person{ * //单例对象object,构造类似class //编译后伴生对象,成为静态成员 public static int newpersonid()*
private var lastid = 0
def newpersonid() = {
lastid+=1
lastid
}
def main(args:Array[String]){ * //应用程序对象(程序从此运行)
val person1 = new person("大刘") *//调用了person类的apply方法
val person2 = new person("小刘")
person1.info()
person2.info()
}
}

对象的apply,update方法

var myarr = Array("hadoop","spark") *//调用了Array类的apply方法
var myarr = new Array[String](3)
myarr(0) = "me" myarr(1)= "you" myarr(2) = "they" *//调用了Array类的update方法(使用了括号,实际上执行了myarr.update(0,"me"))

(2) 继承

抽象类

abstrate class Car{               * //抽象类
val carband:String * //抽象字段
def info() * //抽象方法
def greeting() {
println("welcome")
}
}
class BWM extends Car{
override val carband = "BWM" * //重写超类的字段需要使用override
def info() {printf("this is a %s car",carband)} * //重写超类的抽象函数,不必使用override
override def greeting() {
println("welcome to BWM") * //重写超类的非抽象函数,不必使用override
}
object Mycar{
def main(args:Array[String]){
val car = new BWM()
car.info()
car.greeting()
}
}

特质(trait)类似java中的接口,可实现多重继承

trait Car{
var id:Int * //抽象字段
def currid():Int * // 抽象方法
}
trait Greet{
def greeting(para:String){
println("welcome to "+para)
} * //非抽象方法 class BWM entends Car with Greet{ * //多重继承
override var id = 1000
def currid():Int = {
id+=1;id
}
}
object Mycar{
def main(args:Array[String]){
val car1 = new BWM()
car1.currid()
car1.greeting("BWM")
}
}
05-28 12:44