2021-04-12 15:12:09
浏览数 (1)
继承override
代码语言:javascript
复制//覆盖父类的field或者方法一定要加override
class BankAccount(val initialBalance: Double) {
private var balance = initialBalance
def deposit(value: Double) = {
balance = value
balance
}
def withdraw(value: Double) = {
balance -= value
balance
}
}
class CheckingAccount(override val initialBalance: Double) extends BankAccount(initialBalance) {
private var balance = initialBalance
override def deposit(value: Double) = {
balance -= 1
balance = value
balance
}
override def withdraw(value: Double) = {
balance -= 1
balance -= value
balance
}
}
class SavingAccount(override val initialBalance: Double) extends BankAccount(initialBalance) {
private var balance = initialBalance
private var freeProcess = 3
private val monthlyInterestRate = 0.01
private def checkFreeProcess = {
if (freeProcess > 0) {
freeProcess -= 1
false
} else {
true
}
}
private def earnMonthlyInterest = {
freeProcess = 3
balance = balance * monthlyInterestRate
balance
}
override def deposit(value: Double) = {
if (checkFreeProcess)
balance -= 1
balance = value
balance
}
override def withdraw(value: Double) = {
if (checkFreeProcess)
balance -= 1
balance -= value
balance
}
抽象
代码语言:javascript
复制abstract class Item {
//抽象filed和method不用abstract修饰
def price: Double
def description: String
}
//def只能重写另一个def
//val可以重写另一个val还有def
//var只能重写另一个抽象var
class SimpleItem(val price: Double, val description: String) extends Item {
override def toString = {
"[" description ":" price "]"
}
}
class Bundle extends Item {
private val items = ArrayBuffer[Item]()
def addItems(item: Item) = {
items = item
items
}
def price = {
var amount = 0.0;
for (i <- items) {
amount = i.price
}
amount
}
def description = {
items.mkString("")
}
}
object Item{
def test = {
val item1 = new SimpleItem(9.9,"pencil")
val item2 = new SimpleItem(99.9,"pen")
val items = new Bundle
items.addItems(item1)
items.addItems(item2)
println(items.description)
}
}