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
}
2.编写一个BankAccount类,加入deposit和withdraw方法,和一个只读的balance属性。
class BankAccount(val balance:Int = 0){
def deposit(){print("deposit")}
def withdraw(){print("withdraw")}
}
3.编写一个Time类,加入只读属性hours和minutes,和一个检查某一时刻是否早于另一时刻的方法before(other:Time):Boolean。Time对象应该以new Time(hrs,min)
class Time(val hours:Int,val minutes:Int){
def before(other:Time):Boolean={
hours < other.hours || (hours == other.hours && minutes < other.minutes )
override def toString():String={
hours + ":" + minutes
}
}
}
4.重复实现前一个练习中的Time类,将内部呈现改成自午夜起的分钟数(介于0到24*60-1之间)。不要改变公有接口。也就是说,客户端代码不应因你的修改而受到影响。
class Time(val hours:Int,val minutes:Int){
def before(other:Time):Boolean={
hours < other.hours || (hours == other.hours && minutes < other.minutes)
}
override def toString():String={
hours*60 + ":" + minutes
}
}
5.创建一个Student类,加入可读写的JavaBeans属性name(类型为String)和id(类型为Long),有哪些方法被生成?(用javap查看。)你可以在Scala中调用JavaBeans版的getter和setter方法吗?应该这样做吗?
import scala.beans.BeanProperty
class Student{
@BeanProperty var name = _
@BeanProperty var id = _
}
不知道为什么每次用javap的时候一直提示类找不到类。
6.在5.2节的Person类中提供一个住构造器,将年龄转换为0。
class Person(var age:Int){
age = if(age < 0) 0 else age
}
7.编写一个Person类,其主构造器接受一个字符串,该字符串包含名字、空格和姓,如new Person(“Fred Smith”)。提供制度属性firstName和lastName。主构造器参数应该是var、val还是普通参数呢?为什么?
应该是val,因为如果是var则会有get和set的默认方法,可是其属性是不能改变的,所以只能为val的属性。
8.创建一个Car类,以只读属性对应制造商、型号名称、型号年份以及一个可读写的属性用于车牌。提供四组构造器。每一个构造器都要求制造商和型号名称为必填。型号年份以及车辆为可选,如果未填,则型号年份设置为-1,车辆设置为空字符串。你会选择哪一个作为你的主构造器?为什么?
class Car(val Product:String,val Name:String,val Year:Long = -1,var Number:String = ""){
if(Product == null || Name == null) return 1
}
10.重写该类,使用显式的字段定义,和一个缺省主构造器。你更倾向于使用哪一种形式?为什么?
class Employee{
val name:String = "John Q. Public"
var salary:Double = 0.0
}
不知道这么写对不对,总感觉有点怪怪的
如果是按照这种形式来写的话,确实是第二种的形式更加的方便,清晰。