1. 扩展如下的BankAccount类,新类CheckingAccount对每次存款和取款都收取1美元的手续费class BankAccount(initialBalance:Double){
class BankAccount(initialBalance:Double) {
private var balance =initialBalance
def deposit(amount:Double)={balance+=amount ; balance}
def withDraw(amount:Double)={balance-=amount; balance}
}
//拓展这个类,每次都收1元手续费
class OtherBankAccount(initialBalance:Double) extends BankAccount(initialBalance){
private var balance =initialBalance
override def deposit(amount:Double)=super.deposit(amount-1)
override def withDraw(amount:Double)=super.withDraw(amount+1)
}
2. 扩展前一个练习的BankAccount类,新类SavingsAccount每个月都有利息产生(earnMonthlyInterest方法被调用),并且有每月三次免手续费的存款或取款。在earnMonthlyInterest方法中重置交易计数。
class SavingsAccount(initialBalance:Double) extends BankAccount(initialBalance){
private var num:Int = _
def earnMonthlyIntersert()={
num=3
//利息
super.deposit(1)
}
override def deposit(amount: Double): Double = {
num -=1
if(num <0)super.deposit(amount-1) else super.deposit(amount)
}
override def withDraw(amount: Double): Double ={
num -=1
if(num < 0)super.withDraw(amount+1) else super.withDraw(amount)
}
}
3. 翻开你喜欢的Java或C++教科书,一定会找到用来讲解继承层级的实例,可能是员工,宠物,图形或类似的东西。用Scala来实现这个示例。
class Animal {
private String name;
private int id;
public Animal(String myName, int myid) {
name = myName;
id = myid;
}
public void eat(){
System.out