Scala类
1. 单例对象:
单例(Singleton)对象是一个通过使用“object
关键字”而不是使用“class
关键字”声明的对象。单例对象中声明的方法可以全局访问。在调用单例对象方法时不需要创建对象。
object SingletonObject{
def hello(){
println("Hello, This is Singleton Object")
}
}
object Test {
def main(args: Array[String]){
SingletonObject.hello(); // No need to create object.
}
}
// 运行结果
Hello, This is Singleton Object
但如果单例对象的apply函数返回的是类的一个对象是,可以创建一个对象
case class Company(name: String)
object Person {
def apply(name: String): Company = new Company(name)
}
object Test{
def main(args: Array[String]){
val c:Company = Person("HW") // 由于返回的是类Company的一个对象, 所以可以创建对象 c
println("c.name = " + c.name)
}
}
// 运行结果
c.name = HW
2. Scala final类示例
final
类不能继承。 如果定义了一个类为final
类,那就不能进一步扩展了。
final class Vehicle{
def show(){
println("vehicle is running")
}
}
class Bike extends Vehicle{
override def show(){
println("bike is running")
}
}
object Demo{
def main(args:Array[String]){
var b = new Bike()
b.show()
}
}
// 运行结果
scalac Demo.scala
Demo.scala:8: error: illegal inheritance from final class Vehicle
class Bike extends Vehicle{
^
one error found
3. Scala final方法
在父类中的final
方法声明不能被覆盖。 如果不想让它被覆盖,则可以把方法定义成为final
。尝试覆盖final
方法将导致编译时错误。
class Vehicle{
final def show(){
println("vehicle is running")
}
}
class Bike extends Vehicle{
//override val speed:Int = 100
override def show(){
println("bike is running")
}
}
object Demo{
def main(args:Array[String]){
var b = new Bike()
b.show()
}
}
// 运行结果:
scalac Demo.scala
Demo.scala:8: error: overriding method show in class Vehicle of type ()Unit;
method show cannot override final member
override def show(){
^
one error found
4. 抽象类
你可以定义一个抽象类(abstract class),它定义了一些方法但没有实现他们。取而代之的是有扩展抽象类的子类定义这些方法。不能创建抽象类的实例
scala> abstract class Shape {
| def getArea():Int // subclass should define this
| }
defined class Shape
scala> class Circle(r: Int) extends Shape {
| def getArea():Int = { r * r * 3 }
| }
defined class Circle
scala> val s = new Shape
<console>:8: error: class Shape is abstract; cannot be instantiated
val s = new Shape
^
scala> val c = new Circle(2)
c: Circle = Circle@65c0035b