//scala的访问权限 class House() { var money = 100 private var password = "123456" protected var car = "su7" def say(): Unit = { money = 200 password = "12" car = "xiaoming" } } //伴生对象 object House { def test(house: House): Unit = { house } } //子类 class BigHouse extends House { def test(): Unit = { //super. 子类访问父类的方法 // super.say() // super.money // super.car } } //属性的访问修饰符:(1)无修饰符-不做任何限制 (2)private (3) protected (4)private[this] // 类的内部方法 伴生对象中的方法 类的外部(对象.访问) 子类对象.访问 子类方法是否可以访问 另一个对象.属性 // 无修饰符 可以 可以 可以 可以 可以 // private 可以 可以 不可以 不可以 不可以 // protected 可以 可以 不可以 不可以 可以 // private[this] 可以 不可以 不可以 不可以 不可以 不可以 object dhfg { def main(args: Array[String]): Unit = { var h1 = new House() println(h1.money) h1.money h1.say() var h2 = new BigHouse() h2.money h2.say() } }
package Scala4 //银行的转账 //账户类 class Account(private[this] var balance:Double){ //查余额 def showMoney(): Double ={ balance } //存钱 def deposit(amount: Double): Unit ={ balance+=amount } // def withposit(amount:Double): Unit ={ // balance+=amount // } //取钱 def withdraw(amount:Double): Unit ={ if(balance>=amount){ balance-=amount } } //转账 //把自己的钱减少-->把别人的钱增加 def trans(to:Account,amount:Double): Unit ={ if(balance>=amount){ balance-=amount to.deposit(amount) // to.balance+=amount } } //直接去修改另一个对象的属性 def clear(to:Account): Unit ={ // to.balance=0 } } object Account{ def test(account: Account): Unit ={ account } } object gdhasdj { def main(args: Array[String]): Unit = { var xiaohua=new Account(10000000) var xiaoming=new Account(50000) //不允许外部直接修改 xiaohua.trans(xiaoming,2000) xiaohua.clear(xiaoming) println(xiaohua.showMoney) println(xiaoming.showMoney()) } }