package com.uplooking.bigdata.p2
/**
* scala中关于伴生对象和伴生类的说明
* 要想让伴生类和伴生对象创建的相关对象访问相应的成员,需要在伴生类和伴生对象中创建一个方法apply
* 在伴生对象中要创建,实际apply最好写上括号,在用伴生对象创建对象的时候就可以省略new关键字
* 在apply方法中,创建一个伴生类的对象即可
*/
object CompanionObjectOps {
def main(args: Array[String]): Unit = {
val customer = new Customer()//通过伴生类来创建的对象
val customer1 = Customer() //这是通过伴生对象来创建的对象--->其实质还是调用了ojbect Customer中的apply()方法
val money = customer.withdraw(2000)
println(money)
// customer1.apply.withdraw(200)
// customer.apply.save()
// customer.
customer1.withdraw(200)
}
}
/**
* 所谓伴生对象,就是和某一个class同名的object,并且这个class和object必须在同一个scala源文件中存在,
* 依次来满足类似于java中的一个类中既可以有静态的成员,也可以有非静态的成员
* 把这个object就叫做了这个class的伴生对象
* 把这个class就叫做了这个object的伴生类
*
* 在伴生类和伴生对象中可以互相调用互相的私有成员
*/
class Customer {
private var cAccount = Customer.account
def withdraw(money:Double): Double = {
if(money > cAccount) {
throw new RuntimeException("余额不足,请确认后再取钱~")
}
cAccount -= money
println("当前账户余额:" + cAccount + "¥")
money
}
def apply():Customer = {
println("---------customer apply------------")
val c = Customer()
c
}
}
object Customer {
private var account = 5000.0
def save(money:Double): Unit = {
account += money
println("当前账户余额:" + account + "¥")
}
//在伴生对象中写一个方法apply,然后就可以在伴生对象中调用伴生类中的成员,返回值为伴生类
//
def apply(): Customer = new Customer()
}
/**
* scala中关于伴生对象和伴生类的说明
* 要想让伴生类和伴生对象创建的相关对象访问相应的成员,需要在伴生类和伴生对象中创建一个方法apply
* 在伴生对象中要创建,实际apply最好写上括号,在用伴生对象创建对象的时候就可以省略new关键字
* 在apply方法中,创建一个伴生类的对象即可
*/
object CompanionObjectOps {
def main(args: Array[String]): Unit = {
val customer = new Customer()//通过伴生类来创建的对象
val customer1 = Customer() //这是通过伴生对象来创建的对象--->其实质还是调用了ojbect Customer中的apply()方法
val money = customer.withdraw(2000)
println(money)
// customer1.apply.withdraw(200)
// customer.apply.save()
// customer.
customer1.withdraw(200)
}
}
/**
* 所谓伴生对象,就是和某一个class同名的object,并且这个class和object必须在同一个scala源文件中存在,
* 依次来满足类似于java中的一个类中既可以有静态的成员,也可以有非静态的成员
* 把这个object就叫做了这个class的伴生对象
* 把这个class就叫做了这个object的伴生类
*
* 在伴生类和伴生对象中可以互相调用互相的私有成员
*/
class Customer {
private var cAccount = Customer.account
def withdraw(money:Double): Double = {
if(money > cAccount) {
throw new RuntimeException("余额不足,请确认后再取钱~")
}
cAccount -= money
println("当前账户余额:" + cAccount + "¥")
money
}
def apply():Customer = {
println("---------customer apply------------")
val c = Customer()
c
}
}
object Customer {
private var account = 5000.0
def save(money:Double): Unit = {
account += money
println("当前账户余额:" + account + "¥")
}
//在伴生对象中写一个方法apply,然后就可以在伴生对象中调用伴生类中的成员,返回值为伴生类
//
def apply(): Customer = new Customer()
}