//课后题第一题
class counter{
private var MaxValue=0
def current_value:Int=MaxValue
def increase(): Unit ={
if (MaxValue<Int.MaxValue) MaxValue+=1
}
}
//课后题第二题
class BankAccount{
private var balance_money=0
def balance: Int =balance_money //只读就给一个getter咯,setter是私有的
def deposit(d_money:Int): Unit ={
balance_money+=d_money
println("存款成功")
}
def withdraw(w_money:Int): Unit ={
if(w_money>balance_money)println("余额不足,账户余额还剩$元",balance_money)
else {
balance_money -= w_money
println("取款成功")
}
}
}
//课后题第三题
/*class Time(hours:Int,minutes:Int){
private var hour=if(0<=hour && hours<=23)hours else -1
def before(other:Time): Boolean={
other.hours>hours||other.hours==hours&&other.minutes>minutes //只读属性--val
}
}*/
//课后题第四题
class Time(val hours:Int,val minutes:Int){
private val hour=if(hours >=0 && hours<=23)hours else -1
def before(other:Time): Boolean={
(other.hour*60+other.minutes) > (hour*60+minutes) //只读属性--val
}
}
//第五题
class Student{
@BeanProperty var name:String=_
}
//第六题
/*class Person(var age:Int){
if(age<0) age=0
}*/
//第七题
class person(full_name:String){
private val num=full_name.split(" ")
val lastName,firstName=num(0);num(1)
}
//主构造器参数应该为val 因为有var/val--编译器会自动生成一个字段,相当于直接在类里面定义了,不加val/var--分两种情况-如果被类中的参数调用---对象私有的不可变字段--不被调用--普通参数
//第八题:
class Car(val manufacturer:String,val model:String){
private var typeYears = -1
private var cards=" "
def card:String=cards
def card_=(newCard:String): Unit = {cards=newCard} //可读写--- //匿名函数
def typeYear:Int=typeYears
def this(manufacturer:String,model:String,card:String){
this(manufacturer,model)
this.cards=card
}
def this(manufacturer:String,model:String,year:Int){
this(manufacturer,model," ")
this.typeYears=year
}
def this(manufacturer:String,model:String,card:String,year:Int){
this(manufacturer,model,card)
this.typeYears=year
}
}
//因为构造器是一个套着一个且有且仅有一个辅助构造器调用辅助构造器,也就是说主构造器必须执行--主构造器的参数的字段必须生成
//又想只读,而在编写程序时又要改变初值---给私有化并给一个public的getter
快学Scala-第二版-第五章课后习题
最新推荐文章于 2024-07-29 13:25:32 发布