Scala学习笔记10【对象私有字段、Scala构造器、内部类】

Scala类的属性 和 对象私有字段

class Person{

    //默认public
    private var age = 0   //必须赋予初值
    def increment() { age += 1 }
    def current = age   //无参数方法可省略“()”
}

class Student{
    //对象私有字段
    private[this] var privateAge = 0  //仅限Student使用,子对象不能使用
    val name = "Scala"
    def age = privateAge

    def isYounger(other: Student) = privateAge < other.privateAge //错误,other不能使用privateAge
}


object ScalaOOP{
    def main(args: Array[String]): unit = {
        val person = new Person()  //构建Person对象
        person.increment()
        println(person.current)  //输出1

        val student = new Student
        println(student.name) //输出 Scala
        println(student.privateAge) //错误,privateAge为对象私有字段,无法访问
    }
}

Scala构造器

1、类名无参数

class Teacher{
    var name : String = _   
    private var age = 27
    private[this] val gender = "male"

    //构造器重载
    def this(name: String){
        this()  //必须调用默认构造器
        this.name = name
    }

    def sayHello(){
        println(this.name + ":" + this.age + ":" + this.gender)
    }
}

object ScalaConstructor{
    def main(args: Array[String]): unit = {
        val p = new  Teacher
        p.name = "Spark"
        p.sayHello
    }
}

2、类名有参数

class Teacher(val name: String, val age: Int){   //主构造器
    println("This is the primary constructor!")
    var gender: String = _
    println(gender)


    def this(name: String, age: Int, gender: String){
        this(name, age)  //必须调用主构造器
        this.gender = gender
    }
}

//加上private表示禁止调用默认构造器
class Teacher private (val name: String, val age: Int){} 

object ScalaConstructor{
    def main(args: Array[String]): unit = {
        val p1 = new  Teacher("Scala", 5) //默认构造器
        val p2 = new Teacher("Scala", 23, "male") //重载构造器
    }
}

Scala内部类

Java语言的内部类和Scala语言的内部类有本质的区别:
Java语言的内部类是从属于外部类的,而Scala语言的内部类是从属于外部类的每个具体实例对象的。

class Outer(val name: String){ outer =>
           class Inner(val name: String){
             def foo(b: Inner) = println("Outer: " + outer.name +
                                            "Inner: " + b.name)
           }
}

object ScalaInnerClass{
    def main(args: Array[String]): unit = {
        val outer1 = new Outer("Spark")
        val outer2 = new Outer("Hadoop")
        val inner1 = new outer1.Inner("Scala")  //构建内部类对象的形式
        val inner2 = new outer2.Inner("Java")

        inner1.foo(inner1)
        inner2.foo(inner2)
    }
}

运行结果:

Outer: Spark Inner: Scala
Outer: Hadoop Inner: Java

你可能感兴趣的:(scala,Scala构造器,Scala内部类)