Scala在继承上面与java的一些差别:
1、scala重写一个非抽象方法必须加 override关键字
2、只有主构造器可以调用父类的主构造器
类型检查与使用上,不再是使用java的 instanceOf来判断了,而是使用
isInstanceOf来进行判断对象,使用asInstanceOf来转换对象,例如:
If(p.isInstanceOf[A]){
val s = p.asInstanceOf[A]
…
}
这里说明一下,如果p是null上面的判断并不会抛出异常,而是返回false
并且上面的例子中如果p是A的子类对象,也会成功,如果要具体判断p是否是A的对象,而又不包括其子类,可以这样
If(p.getClass== classOf[A])
另外一种更加scala的做法是使用模式匹配
P match {
case s: A => …
case _ =>
}
package demo
/**
* @author Administrator
*
* scala 继承学习
*/
object ScalaExtends {
def main(args: Array[String]): Unit = {
val ca = new CheckingAccount(100)
println(ca.deposit(100))
println(ca.withdraw(80))
}
}
class BankAccount(initialBalance: Double) {
private var balance = initialBalance
def currentBalance = balance
def deposit(amount: Double) = {
balance += amount
balance
}
def withdraw(amount: Double) = {
balance -= amount
balance
}
}
class CheckingAccount(initialBalance: Double) extends BankAccount(initialBalance: Double) {
override def deposit(amount: Double) = {
super.deposit(amount)
factorage(1)
}
override def withdraw(amount: Double) = {
super.withdraw(amount)
factorage(1)
}
def factorage(amount: Double) = {
super.withdraw(1)
}
}
class SavingsAccount(initialBalance: Double) extends BankAccount(initialBalance: Double) {
private var freeCount: Int = 3
val currentBlance = super.currentBalance
override def deposit(amount: Double) = {
factorage(1)
super.deposit(amount)
}
override def withdraw(amount: Double) = {
factorage(1)
super.withdraw(amount)
}
def factorage(amount: Double) {
if (freeCount <= 0) {
super.withdraw(1)
} else {
freeCount = freeCount - 1
}
}
def earnMonthlyInterest = {
//按月利0.3%结息
val v = currentBlance * 0.003
super.deposit(v)
freeCount = 3
}
}