1. 程式人生 > >Scala——類的定義、重新實現toString方法、檢查先決條件、新增欄位、私有方法、自指向、輔助構造器、操作符、過載、隱式轉換

Scala——類的定義、重新實現toString方法、檢查先決條件、新增欄位、私有方法、自指向、輔助構造器、操作符、過載、隱式轉換

/**
 * Created by jiaoshuhai on 2018/4/23.
 */
//類的建立
class Rational(n:Int,d:Int){//類引數,oject無引數


  //檢察先決條件
  require(d != 0)


  private def gcd(a : Int ,b :Int) : Int =
    if(b == 0) a else gcd(b , a % b)


  //私有欄位和方法
  private val g = gcd(n.abs,d.abs)




  // 新增欄位
  val number : Int = n / g
  val denom : Int = d / g


  //重新實現toString方法
  override def toString = number + "/" + denom


  def add(that: Rational): Rational = {


    new Rational(number * that.denom + that.denom,
      denom * that.denom)
  }


  //自指向
  def lessthan(that : Rational)={
    number * that.denom  < that.number * denom //this可以省略
  }


  //自指向
  def max(that :Rational) : Rational ={


    if (this.lessthan(that)) that else this //this 不可以省略
  }


  def this(n:Int) = this(n,1) //輔助構造器,每個輔助構造器都是以this開頭


  //定義操作符
  def + (that:Rational) : Rational = {
    new Rational(number * that.denom + that.denom,
      denom * that.denom)
  }


  // +,*的優先順序誰高,*
  def * (that : Rational) : Rational ={
    new Rational(number *that.number,denom*that.denom)
  }


  //方法過載
  def * (i : Int) : Rational ={
    new Rational(number *i,denom)
  }