Scala的类和Java类的定义有一些相似之处,也有一些差异。
1、基础概念
我们看一个Scala定义类的简单例子,在这个例子里,定义了两个变量 x
,y
,还有一个move
方法
class Point(xc: Int, yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int): Unit ={
x = x + dx
y = y + dy
println("x 的坐标点:" + x)
println("y 的坐标点:" + y)
}
}
object Test{
def main(args: Array[String]) {
val pt = new Point(10, 12) // 实例化对象
pt.move(2, 3) // 调用 move方法
}
}
这个例子里可以看到Scala和Java一个明显的差异是在构造函数上,Scala使用类的名称作为一个类构造函数。
2、扩展类(继承)
在上面的例子基础上,我们增加一个新类 Location
,Location
类继承了 Point
类,并且重写了 move
方法。Scala继承和Java里继承相似,但是有两个限制,方法重写需要 override
关键字,只有主构造函数可以通过参数调用基类构造函数。
class Point(xc: Int, yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int): Unit ={
x = x + dx
y = y + dy
println("x 的坐标点:" + x)
println("y 的坐标点:" + y)
}
}
class Location(val xc:Int, val yc:Int, val zc: Int) extends Point(xc, yc){
var z:Int = zc
def move(dx:Int, dy:Int, dz:Int): Unit ={
x = x + dx
y = x + dy
z = z + dz
println("x 的坐标点:" + x)
println("y 的坐标点:" + y)
println("z 的坐标点:" + z)
}
}
object Test{
def main(args: Array[String]) {
val pt = new Point(10, 12) // 实例化对象
pt.move(2, 3) // 调用 move方法
println()
val lc = new Location(1,2,3) // 实例化对象
lc.move(3,3,3) // 调用 move方法
}
}
这里不单独细讲 override
的使用,后续笔记里会单独整理。
3、单例对象
Scala比Java更面向对象,因为在Scala中不能拥有静态成员,Scala它使用单例对象。单例是一种只能有一个实例的对象。使用 object
关键字对象而不是类关键字创建单例。由于无法实例化单例对象,因此无法将参数传递给主构造函数。
class Point(xc: Int, yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int): Unit ={
x = x + dx
y = y + dy
println("x 的坐标点:" + x)
println("y 的坐标点:" + y)
}
}
object Test{
def main(args: Array[String]) {
val pt = new Point(10, 12)
pt.move(2, 3)
println()
SingletonObject.hello
}
}
// 单例对象
object SingletonObject{
def hello: Unit ={
println("hello world, this is Singleton object!")
}
}
也可以将 hello
方法定义在主方法内,
class Point(xc: Int, yc: Int) {
var x: Int = xc
var y: Int = yc
def move(dx: Int, dy: Int): Unit ={
x = x + dx
y = y + dy
println("x 的坐标点:" + x)
println("y 的坐标点:" + y)
}
}
object Test{
def main(args: Array[String]) {
val pt = new Point(10, 12)
pt.move(2, 3)
println()
hello // 调用hello方法
def hello: Unit ={
println("hello world, this is Singleton object!")
}
}
}