field
代码语言:javascript
复制class Counter {
//field必须初始化,为了知道类型
//会自动生成private的getter还有private的setter
//setter和getter并不是getValue()和setValue()这样,而是value(),value_=()这样
private var value = 0
def increment() = {
value = 1
}
def current() = value
//类私有field可以访问
def largerThan(a: Counter): Boolean = {
value > a.value
}
//对象私有field别的对象无法访问
private[this] var name = "test"
def setName(name: String) = {
this.name = name
}
//会自动生成public的getter和setter
var times = 0
//会自动生成public的getter
val alloc = "hash"
}
object Counter1 {
val counter = new Counter
def testClass = {
//习惯上取值器不加括号
println(counter.current)//输出:0
//习惯上改值器加括号
counter.increment()
println(counter.current)//输出:1
val counter2 = new Counter
println(counter.largerThan(counter2))//输出:true
}
}
Constructor
代码语言:javascript
复制//main constructor
class Person(val name: String, var age: Int, var salary: Int) {
//主构造器会执行所有语句
println("Main constructor is called!")
//多态构造器
def this(name: String, age: Int) {
this(name, age, 0)
}
def description = "Name: " name ", Age: " age ", Salary: " salary
}
object Person1 {
def test = {
val person = new Person("zhxhash", 24, 20000)//输出:Main constructor is called!
println(person.description)//输出:Name: zhxhash, Age: 24, Salary: 20000
val person2 = new Person("zhxdick", 15)//输出:Main constructor is called!
println(person2.description)//输出:Name: zhxdick, Age: 15, Salary: 0
}
}
练习:
代码语言:javascript
复制object Exercise {
class Counter(private var value: Int = 0) {
def increment() = {
if (value == Int.MaxValue)
value = 0
else
value = 1
}
def current = value
}
def ex01 = {
val counter = new Counter(Int.MaxValue)
counter.increment()
println(counter.current)//输出:0
}
class BankAccount(private var balance: Double) {
def currentBalance = balance
def deposit(value: Double) = {
balance = value
}
def withdraw(value: Double) = {
balance -= value
}
}
def ex02 = {
val bankAccount = new BankAccount(100000)
bankAccount.deposit(99)
bankAccount.withdraw(88)
println(bankAccount.currentBalance)//输出:100011.0
}
class Time(private val hours: Int, private val minutes: Int) {
if (hours < 0 || hours > 23 || minutes < 0 || minutes > 59)
throw new IllegalArgumentException()
def before(other: Time): Boolean = {
(hours > other.hours) || ((hours == other.hours) && (minutes > other.minutes))
}
def description = "[" hours ":" minutes "]"
}
def ex03 = {
val time = new Time(13, 59)
val time2 = new Time(13, 25)
val time3 = new Time(14, 25)
println(time.description time2.description time.before(time2))//输出:[13:59][13:25]true
println(time.description time3.description time.before(time3))//输出:[13:59][14:25]false
}
}