scala语言中没有static成员存在,但是scala允许以某种方式去使用static成员
这个就是伴生机制,所谓伴生,就是在语言层面上,把static成员和非static成员用不同的表达方式,class和object,
但双方具有相同的package和name,但是最终编译器会把他们编译到一起,这是纯粹从语法层面上的约定。通过javap可以反编译看到。
另外一个小魔法就是单例,单例本质上是通过伴生机制完成的,直接由编译器生成一个class对象,这样至少在底层能够统一。
多个构造方法都需要调用默认的构造方法
class User (x:Int,age:Int){//默认构造器 val height = x; val this.age = age; var name =""; def this(){ this(5,5); } def this(t1:Int,t2:Int,name:String){ this(5,5); this.name= name; } }
class和object的调用方式
class TestObject private{ val t2 = "lskjdfkljd" var t=123 def func01() = { println("gaga"); } } object TestObject { val t1 = 123; var ssssgagag=1444; val single = new TestObject(); def func02() = { println("gaga"); } def main(args: Array[String]) { val t1 = new TestObject(); println(t1.t2); t1.func01(); TestObject.func02(); println(TestObject.t1) println(TestObject.ssssgagag) } }
类的继承和trait
trait Listen{ val name: String def listen() = { println("You friend " + name + " is listening") } } trait Read{ val name: String def read() = { println("You friend " + name + " is reading") } } trait Speak{ val name: String def speak() = { println("You friend " + name + " is speaking.") } } class Human(val name : String){ def listen() = { println(name + " is listening.") } } class Animal(val name: String){ } class Cat(override val name: String) extends Animal(name: String) with Speak with Listen with Read{ override def toString(): String = " hello "+name+"! " } object TestFriend { def main(args: Array[String]) { val f1 = new Listen();//java 接口很像 不能直接够造 val h1 = new Human("gaga"); h1.listen(); //这样scat就是Friend了 val scat = new Cat("hello kitty") scat.listen(); scat.speak() println(scat) } }