当前位置:网站首页>Scala advanced_ Member access modifier

Scala advanced_ Member access modifier

2022-06-27 06:20:00 Big data interview classic


Access modifier

and Java equally ,scala You can also access the modifier , To control whether member variables and member methods can be accessed .

Definition

Java Access control in , The same applies scala, You can add... Before a member private/protected Keyword to control the visibility of members . But in scala in ,​ No, public keyword ​, Anything not marked as private or protected All members are public

Case study


  • Define a Person class
    [ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-vq1JjDij-1581824772468)(assets/1557664595693.png)]
  • stay main Method , Test for access to private members

Reference code

       
object _02AccessDemo {

class Person {
// Define private member variables
private var name:String = _
private var age:Int = _

def getName() = name
def setName(name:String) = this.name = name
def getAge() = age
def setAge(age:Int) = this.age = age

// Private member definition method
private def getNameAndAge = {
name -> age
}
}

def main(args: Array[String]): Unit = {
val person = new Person
person.setName(" Zhang San ")
person.setAge(10)

println(person.getName())
println(person.getAge())
}
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.



原网站

版权声明
本文为[Big data interview classic]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202161659093800.html