覆盖方法
到目前为止,我们继承的类都没有真正执行任何能够使彼此有所区分的操作
package com.test1 object Scala09_test13 { def main(args: Array[String]): Unit = { //地道的scala //定义操作符 //方法名可以包含几乎所有字符。例如,在创建数学包时,你可以按照数学家的方式 class Molecule{ //var name = _ (前提必须是变量var 不能是val) var attached:Molecule = _ def plus(other:Molecule)=attached=other def +(other:Molecule)=attached=other } var m1 = new Molecule var m2 = new Molecule println(m1.plus(m2)) println(m1.+(m2)) //这个类对称为 //注意,在第 import language.postfixOps class Swearing{ def #!>% = "Rowzafrazca" } val x = new Swearing println(x.#!>%) println(x.#!>%) //自动字符串转换 //case类可以将对象连同其参数恰当地格式化为适于显示的形式 case class Bicycle(riders:Int) val forTwo = Bicycle(2) println(forTwo.riders) println(forTwo) //在创建case类时会自动创建称为toString的方法,无论何时。无论何时,只要你对某个对象进行操作 //并希望它是一个String, class Surrey(val adorment:String){ override def toString: String = s"Surrey with the $adorment" } val fancy = new Surrey("fringe on top ") println(fancy) //元组 //假设从某个方法返回的结果必须超过一项,例如一个值和有关这个值的一些信息 //伴随对象 //方法作用于类的特定对象 class X(val n:Int){def f = n *10} object X{ val n = 2 def f = n*10 def g = this.n*20 } val x1 = new X(1) val x2 = new X(2) //在调用f,必须在某个对象调用它。在调用过程中,f可以直接访问该对象的成员 println(X.n) println(X.f) println(X.g) //基类初始化 // Scala 通过确保所有构造器都会被调用来保证正确的对象创建过程 class GreatApe(val weight:Double,val age:Int) class Bononbo(weight:Double,age:Int) extends GreatApe(weight,age) class Chimpanzee(weight:Double,age:Int) extends GreatApe(weight,age) class BonoboB(weight:Double,age:Int) extends Bononbo(weight,age) def display(ape: GreatApe)=s"weight:${ape.weight} age:${ape.age}" println(display(new GreatApe(100,12))) println(display(new Bononbo(100,12))) println(display(new Chimpanzee(100,12))) println(display(new BonoboB(100,12))) class House(val addrees:String,val state:String,val zip:String){ def this(state:String,zip:String)={ this("address?",state,zip) } def this(zip:String)={ this("address?","state?",zip) } } class Home(addrees:String,state:String,zip:String,val name:String) extends House(addrees,state,zip){ override def toString: String = s"$name:$addrees,$state,$zip" } class VacationHouse(state:String,zip:String,val startMonth:Int,val endMonth:Int) extends House(state,zip) class TreeHouse(val name:String,zip:String) extends House(zip) val h = new Home("888 N. Main st.","KS","66632","Metropolis") } }
枚举
枚举是名字的集合,scala的Enumeration类提供了一种管理这些名字的便捷。
抽象类:
抽象类就像普通类一样,只是其中的一个或多个方法或域不完整的
scala延续了java的做法