类似python元类与apply方法类似python中call方法
class Person(name: String, var age: Int){
println("Person")
//private[this] var age = 18 // 字段必须得初始化
var gender:String=_
def Age=age //这个是方法
def increamen(){age+=1}
def this(name:String, age:Int, gender:String) {
this(name, age) //调用主构造函数
this.gender = gender
}
override def toString() :String = {
this.age+this.gender+this.name
}
}
class Student{
var age: Int = _
private[this] var gender = "male"
private var name: String = _
def getName = this.name
def setName(value:String){this.name=value}
def this(age: Int, name: String) {
this() // 调用主构造函数
this.age = age
this.name = name
}
override def toString(): String ={
this.age+this.name
}
}
// object 类命与class类命相同并且在一个文件中,伴生类,object下的成员都是静态的 ,
若有同名的class,这其作为它的伴生类。在object中一般可以为伴生类做一些初始化等操作
// 使用apply实现单例
object Dog{
private var age = 0
var instance:Dog = null
def Age():Int = {
age += 1
age
}
def apply(): Dog ={
println("obeject ApplyTest---apply()---")
if (instance == null){
instance = new Dog()
}
instance
}
}
class Dog{
var age1 = Dog.age // //Dog.age是object Dog的私有字段
def apply(): Unit ={
println("class Dog ---apply()---")
}
}
object hW{
def main(args:Array[String]): Unit ={
var dog1 = Dog()
println(dog1.age1)
dog1()
var dog2 = Dog()
println(dog1.equals(dog2))
}