private 方法
Scala
package Test22
// 银行账户
class BankAccount(private var balance:Int){
def showMoney():Unit={
println(s"现在的余额是:${balance}")
}
def deposit(money:Int):Unit={
balance += money
}
def withdraw(money:Int):Unit={
if(money <= balance)
balance -= money
}
// 转账
def transfer(to:BankAccount,money:Int):Unit={
// A --200--> B
// A 减少 B 增加
}
}
object Test22_1 {
def main(args: Array[String]): Unit = {
var xiaoming=new BankAccount(0)
var xiaohua = new BankAccount(100)
//存入 200
xiaohua.deposit(200)
//取出 150
xiaohua.withdraw(1500)
//转账给小明
xiaohua.transfer(xiaohua,100)
xiaohua.showMoney()
xiaoming.showMoney()
}
}
private[this]方法
Scala
package Test22
// 银行账户
class BankAccount(private[this] var balance:Int){
def showMoney():Unit={
println(s"现在的余额是:${balance}")
}
def deposit(money:Int):Unit={
balance += money
}
def withdraw(money:Int):Unit={
if(money <= balance)
balance -= money
}
// 转账:把当前的账户的余额转出money给to这个账户
def transfer(to:BankAccount,money:Int):Unit={
// A --200--> B
// A 减少 B 增加
if(money <= balance){
//把自己减少
balance -= money
//把对方增加
// to.balance += money
to.deposit(money)
}
}
// def test(to:BankAccount):Unit={
// to.balance=0
// }
}
object Test22_1 {
def main(args: Array[String]): Unit = {
var xiaoming=new BankAccount(0)
var xiaohua = new BankAccount(100)
//存入 200
xiaohua.deposit(200)
//取出 150
xiaohua.withdraw(1500)
//转账给小明
xiaohua.transfer(xiaohua,100)
xiaohua.showMoney()
xiaoming.showMoney()
// println(xiaohua.balance)
}
}
Scala 的控制方法作用域有5种:
(1)默认访问权限
(2)protected 访问权限
(3)private 访问权限
(4)private[this]访问权限
(5)private[package]访问权限
Scala
package Test22{
class C() {
private[p2] def test(): Unit = {
println("test")
}
}
object Test22_3 {
def main(args: Array[String]): Unit = {
var c1=new C()
c1.test()
}
}
}