Scala学习笔记之类和对象

Scala面向对象编程精要
本文深入探讨Scala的面向对象编程特性,包括类定义、继承、单例对象等核心概念,对比Java,详解Scala的独特之处。

Scala的类和Java类的定义有一些相似之处,也有一些差异。

1、基础概念

我们看一个Scala定义类的简单例子,在这个例子里,定义了两个变量 xy,还有一个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、扩展类(继承)

在上面的例子基础上,我们增加一个新类 LocationLocation 类继承了 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!")
  	}
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值