class Account {
val id = Account.newUniqueNumber()
private var balance = 0.0
def deposit(amount: Double): Double = {
balance += amount
balance
}
def nowBalance = balance;
}
object Account {
private var lastNumber = 0
private def newUniqueNumber() = {
lastNumber += 1
lastNumber
}
}
object Main {
def main(args: Array[String]): Unit = {
val account = new Account
println(account.id)
println(account.deposit(1))
println("=" * 10)
val account1 = new Account
println(account1.id)
println(account1.deposit(10))
println("=" * 10)
println("a " + account.nowBalance + "; b " + account1.nowBalance)
}
}
// ======= 执行结果
1
1.0
==========
2
10.0
==========
a 1.0; b 10.0
// =================使用apply示例===================
package com.gemantic.bigdata
/**
* @author Yezhiwei
* @date 18/1/4
*/
class Student private (val sno: Int, val name: String){
override def toString: String = {
"sno " + sno + " name " + name
}
}
object Student {
private var sno = 0
private def newSno = {
sno += 1
sno
}
def apply(name: String): Student = {
println("call apply method...")
new Student(newSno, name)
}
}
object StudentMain extends App {
// no new
val student1 = Student("Yezhiwei")
println(student1.toString)
println("*" * 10)
val student2 = Student("Yezhiwei")
println(student2.toString)
}
// 运行结果
call apply method...
sno 1 name Yezhiwei
**********
call apply method...
sno 2 name Yezhiwei