One-Way
爱一人,攀一山,追一梦

一、扩展类

  class Persion{
    def display(){
      println("Hello")
    }
    final def display1(){   //声明为final, 不能被重写 override
      println("Hello1")
    }
  }

  class Employee extends Persion{ //extends 扩展,继承Persion
    override def display() {   //override重写 display方法
      println("H")
    }
  }

  val p = new Employee
  p.display()
  p.display1()

 

二、重写方法

  class Persion{
    private var str = ""
    def display(){
      println("Hello")
    }
    final def display1(){   //声明为final, 不能被重写 override
      println("Hello1")
    }
    def info_= (newStr:String){  //info setter方法
      str = newStr
    }
    def info = str     //info getter方法
  }

  class Employee extends Persion{ //extends 扩展,继承Persion
    override def display() {   //override重写 display方法
      println(super.info +" H")
    }
  }

  val p = new Employee
  p.info="hello"
  p.display()
  p.display1()

调用超类的方法使用: super

 

三、类型检查和转换

  class Persion{
  }

  val p = new Persion
  if(p.isInstanceOf[Persion]){  //类型检查
    println("p is instance of Persion")
  }
  else{
    println("p is not instance of Persion")
  }

  if(p.getClass == classOf[Persion]){ //p是 Persion对象,并不是Persion的子类,这样检查
    println("Yes")
  }

 

p is instance of Persion
Yes

 

四、受保护字段和方法

protected 可以被子类访问

 

五、超类的构造

传递到超类的构造函数

  class Employee(name: String, age: Int, val salary: Double) extends
   Persion(name, age)

Scala类可以扩展java类

  class Square(x:Int , y: Int, width: Int) extends
  java.awt.Rectangle(x, y, width, width)

 

六、重写字段

  class Persion(val name: String){
    override def toString = getClass.getName()+ "[name="+name+"]"
  }


  class SecretAgent (codename: String) extends Persion(codename){
    override val name = "secret"   //重写 name
    override val toString ="secret" //重写 toString
  }

  val p = new SecretAgent("hello")
  println(p.name)
  println(p.toString)

 

常用做法:用val重写抽象的def

  abstract class Persion{
    def id :Int = 10
  }

  class Student(override val id:Int) extends Persion{
  }

  val p = new Student(4)
  println(p.id)

 

七、匿名字段

  class Persion(val name:String){
  }

  val alien = new Persion("Fred"){  //匿名子类   类型为 Persion{def greeting: String}
    def greeting = "Hi everybody"
  }

  def meet(p:Persion{def greeting: String}){
    println(p.name + " says:" + p.greeting)
  }

  meet(alien)

结果:

Fred says:Hi everybody

 

八、抽象类

  abstract class Persion(val name:String){ //抽象类
    def id:Int   //方法不用定义为抽象
  }

  class Student(name:String) extends Persion(name){ //继承抽象类
    def id = name.hashCode  //实现抽象类中的方法, 不需要override关键字
  }
  
  val s = new Student("Jim")
  println(s.id)

 

九、抽象字段

  abstract class Persion{
    val id :Int
    var name : String
  }

  class Student(val id :Int) extends Persion{
    var name =""
  }

  val fred = new Persion{
    val id = 12
    var name = "Fred"
  }

  println(fred.id)
  println(fred.name)

结果:

12
Fred

 

十、构造顺序和提前定义

  class Creature {
    val range: Int = 10
    val env: Array[Int] = new Array[Int](range)
  }

  class Ant extends Creature{
    override val range: Int = 2
  }

  val c = new Ant
  println(c.range)              //结果为2
  println(c.env.length)      //结果为0

  class Creature {
    lazy val range: Int = 10    //使用lazy
    val env: Array[Int] = new Array[Int](range)
  }

  class Ant extends Creature{
    override lazy val range: Int = 2  //使用lazy
  }

  val c = new Ant
  println(c.range)            
  println(c.env.length)        //返回结果为2

  class Creature {
      val range: Int = 10
      val env: Array[Int] = new Array[Int](range)
    }

    class Ant extends {            //使用提前定义  with Creature
      override val range: Int = 2
    }with Creature

    val c = new Ant
    println(c.range)
    println(c.env.length)      //结果返回2

 

十一、Scala继承层次

Any 类继承层次根节点

Nothing 类型没有实例

Null 类型的唯一实例是null值

Nil 空列表, 空列表的类型是List[Nothing]

Unit 类型void

 

十二、对象相等性

  class Item(val desc: String, val value: Double){

    final override def equals(other: Any) ={   //参数使用 Any类型 ,重写AnyRef equals方法
      val that = other.asInstanceOf[Item]
      if(that == null) false
      else desc == that.desc &&  value ==that.value  //判断是否相等
    }

    final override def hashCode = 13 * desc.hashCode + 17 * value.hashCode //重写 hashCode方法

  }

  val a = new Item("Apple", 14)

  val b = new Item("Apple", 23)

  if(a == b)
    println("Equal")

 

练习:

1.2.

object Chapter8 extends App{
  
  class BankAccount(initialBalance:Double){
    private var balance = initialBalance
    def deposit(amount:Double) = {balance += amount; balance}
    def withdraw(amount:Double) = {balance -= amount; balance}
    override def toString=s"money=$balance"
  }

  class CheckingAccount(initialBalance:Double) extends BankAccount(initialBalance:Double){
    val fee: Double = 1
    var count:Int = 3
    override def deposit(amount:Double) = {val new_amount=if(count>0) {count-=1;amount-fee} else amount;super.deposit(new_amount)} //存钱,扣除手续费,少存
    override def withdraw(amount:Double) = {val new_amount=if(count>0) {count-=1;amount+fee} else amount;super.withdraw(new_amount)}//取钱,扣除手续费,多扣
    def earnMonthlyInterest(c:Int = 3) {count = c}
  }

  val ba = new CheckingAccount(100)
  ba.deposit(100)
  println(ba)
  
}

4.

object Chapter8 extends App{
  abstract class Item {
    def name:String
    def price:Float
    def description:String
  }

  class SimpleItem (n: String, p: Float) extends Item{
    val name:String = n
    val price = p
    val description = s"$n is $p yuan"
  }

  class Bundle{
    import scala.collection.mutable.ArrayBuffer
    var items = new ArrayBuffer[Item]()

    def price = {
      var sum: Float = 0
      for(i<- items) {
        sum+=i.price
      }
      sum
    }
    def addItem(item:Item){items+=item}
    def description:String={s"price is $price yuan"}
  }
  
  val i1 = new SimpleItem("i1",100)
  val i2 = new SimpleItem("i2",201)

  val b = new Bundle()
  b.addItem(i1)
  b.addItem(i2)
  println(b.price)
}

5.

object Chapter8 extends App{

  class Point(x:Double, y:Double){
  }
  class LabelPoint(label:String, x:Double, y:Double)extends Point(x,y){
  }
  val lp = new LabelPoint("label", 100.21, 200.31)
}

6.

 

 

 

 

参考《快学Scala》

posted on 2016-08-25 14:19  单行道|  阅读(6902)  评论(0编辑  收藏  举报