package chapter5
//5.1 改进5.1节的Counter类,让它不要在Int.MaxValue时变成负数
//增加一个判断
class Counter {
private var value = 0
def increment() {
if (value < Int.MaxValue) value+1 else value
}
def current = value
}
//5.2写一个BankAccount类,加入deposit和withdraw方法,和一个只读的balance属性
class BankAccount {
private val balance = 0
def deposit() {}
def withdraw() {}
}
//5.3编写一个Time类,加入只读属性hours和minutes,和一个检查某一时刻是否早于另一时刻的方法before(other:Time):Boolean。
// Time对象应该以new Time(hrs,min)方式构建。其中hrs以军用时间格式呈现(介于0和23之间)
//这里使用required 来进行异常参数检查
class Time(val hours: Int, val minutes: Int) {
require(hours >= 0 && hours <= 23 && minutes >= 0 && minutes <= 59)
def before(other:Time):Boolean={
hours < other.hours || (hours == other.hours && minutes < other.minutes)
}
}
//5.6.在5.1节的Persion类中加一个主构造器,将负年龄换为0
class Persion(page:Int){
var age:Int = 0
if(page < 0){
age = 0
}else{
age = page
}
def getAge():Int = age
}
object Test {
def main(args: Array[String]): Unit = {
val time1=new Time(11,11)
val time2=new Time(10,11)
println(time1.before(time2))
}
}