Trait
/**
*1. tarit 作用相当于java中的接口 或者抽象类(java中是单继承)
* 2. tarit 中有自己的属性 和方法以及实现方法
* 3. tarit 不可以传参(构造参)
*/
trait TestScalaTrait01 {
val str = "str"
val num = 1
def str(str: String) :Unit = {
println(this.str + " = "+ str)
}
def str1(String: String): String
}
trait TestScalaTrait02 {
def getNum(a: Int,b: Int) :Int
}
抽象类
/**
* 抽象类,特点和tarit很相似,不过只能单继承
*/
abstract class TestAbstract1{
var ss = "121"
def getValue(str: String)
def getValue2(mess: String) :String = mess
def getValue3(): String = ss
}
/**
* 抽象类中可以带构造参数
*/
abstract class TestAbstract2(str: String,i: Int){
val mess = str
val sum = i
def getMess(): String = mess
def getSum(): Int = sum
}
继承
/**
* 继承trait 重写 父类方法 多继承使用with
* 关键字 都是extends
* 只能单继承一个类 或者抽象类
* 同时继承类 和tarit,类应该放在首位
*/
class ClassTestTrait extends TestScalaTrait01 with TestScalaTrait02{
override def str1(String: String): String = {
this.str + " =" + String
}
override def getNum(a: Int, b: Int): Int = a + b
}
class ClassTestAbstract extends TestAbstract1 with TestScalaTrait02{
override def getValue(str: String): Unit = ???
override def getNum(a: Int, b: Int): Int = ???
}
样例类
/**
* 样例类 关键字 case
* 1.不带参构造数的样例类 已经过时
* 2. 构造参数 默认是val 不可变修饰,默认有getter 方法获取属性值
* 3. 构造参数声明为var 时,默认实现 get set
* 4. 样例类默认实现了 tostring, equals, copy ,hashcode 等方法
* 5. 可以使用new 也可以不适用new
*/
case class Person(var name: String,age: Int){
// 也能有自己的方法
def testCase() : String = {
return this.name + " 的年龄为: " + this.age
}
}
object TestCaseClassObject{
def main(args: Array[String]): Unit = {
var p = new Person("xiaoming",12)
p.name="xiaox"
println(p.toString)
println(p.testCase())
// p.age=11 编译爆红 age是val
}