1. 程式人生 > >scala對象簡單記錄

scala對象簡單記錄

ray 簡單記錄 都在 per t對象 tst bstr err 方法

object Person {

  private val eyeNum = 2

  def getEyeNum = eyeNum

  def main(args: Array[String]): Unit = {
    println(Person.getEyeNum)  // 2
  }

}

  

abstract class Hello(var message:String) {

  def sayHello(name :String)

}

object HelloImpl extends Hello("hello"){

  override def sayHello(name: String): Unit = {
    println(message + "," + name)
  }


  def main(args: Array[String]): Unit = {
    HelloImpl.sayHello("yxj")
  }

}

  

/**
  * 一個類和一個object對象名字相同,都在一個.scala文件中,那麽他們就是伴生類和伴生對象
  *
  * @param name
  * @param age
  */
class People(name:String , age:Int ) {

  def sayHello = println("hi," + name +", your age is " + age + ",your eyeNum is " + People.eyeNum)

}

object People {

  private val eyeNum = 2

  def getEyeNum = eyeNum

}

object objectsTest{

  def main(args: Array[String]): Unit = {
    val yy = new People("yxj" , 30)
    yy.sayHello
  }

}

  

/**
  * object中apply方法的使用,簡化對象創建的過程
  *
  */

class Apple(name:String ,age:Int) {
  println(name + "," + age)
}

object Apple{

  // 伴生對象的apply簡化了創建伴生類的方式
  def apply(name: String, age: Int): Apple = new Apple(name, age)

  def main(args: Array[String]): Unit = {
    val a = Apple("yxj" , 30)
    println(a)

    // 普通的創建類的過程
    val a1 = new Apple("yxj" , 31)
    // 伴生對象定義了apply後,不需要在使用new關鍵字來創建一個類的對象實例了

  }

}

  

scala對象簡單記錄