/**
* 伴生类
* 伴生对象 伴生类之间方法可以互相访问
*/
class Oop1(name:String,age:Int) { // scala默认的主构造函数
println("class Oop1 one")
private var uname:String=name
private var uage:Int=age
private var uaddress:String= _
def this(){
this("",0)
println("无参")
}
def this(name:String){
this(name,0)
}
def this(age:Int){
this("",age)
}
def this(name:String,age:Int,address:String){
this(name,age)
this.uaddress=address
}
def showmsg():Unit={
println("进入到Oop1 class showmsg()方法中")
println(this.uname,this.uage,this.uaddress)
Oop1.showObjectMsg()
Oop1.like
println("进入到Oop1 class showmsg()方法,最后一行")
}
}
/**
* 伴生对象
*/
object Oop1{
println("object Oop1 one")
println("object Oop1 two")
private var like:String="scala"
def apply(name: String, age: Int): Oop1 = new Oop1(name, age)
def apply(name:String): Oop1 = new Oop1(name)
def apply(age:Int): Oop1 = new Oop1(age)
def apply(): Oop1 = new Oop1()
def apply(name: String, age: Int, address:String): Oop1 = new Oop1(name, age, address)
val oop13=Oop1()
def sum(a:Int,b:Int):Int={
println(a,b)
oop13.uage
oop13.showmsg()
a+b
}
def showObjectMsg():Unit={
println("Object Oop1 showObjectMsg")
}
def main(args: Array[String]): Unit = {
println("main one")
val oop1 = new Oop1("wjj",21)
val oop2=new Oop1()
val oop3 = new Oop1("wjj")
val oop4 = new Oop1(21)
val oop5 = new Oop1("wjj",21,"安德门")
val oop11=Oop1("zs",12) //Oop1.apply("zs",12)
val oop12=Oop1("zs")
val oop13=Oop1()
val oop14=Oop1(211)
val oop15=Oop1("zs",21,"安德门")
val i = sum(1,3)
println(i)
println(oop5.uaddress)
println("main end")
}
}
scala 伴生类、伴生对象
最新推荐文章于 2023-03-23 19:25:50 发布