scala学习1

scala学习1_第1张图片
image.png

下面是代码学习例子:

package cn.chinahadoop.scala

class basic2 {

}

class Person(){
  var name : String = _ //会生成get以及set方法
  val age = 10 //只会生成get方法
  private [this] val gender = "male"
}

//主构造器(直接跟在类名称后面):会把类中的所有语句都执行一遍,其参数也会被构造成为类内的变量
//假设参数声明的时候不加val或者var,那么相当于只在类的内部使用,类似于private [this]
class Person2(val name : String, val age : Int){
  var gender : String= _
  val school = "uestc"
  //附属构造器
  def this(name: String, gender : String){
    this(name, 22) //上来第一句还是要先调用主构造器或者已经存在的其他附属构造器
    this.gender = gender
  }
}

//继承的格式要注意以下,name和age都不需要重新加var或者val来进行声明
class Student(name : String, age : Int, var major : String) extends Person2(name, age){
  println("student name : " + name + ", major : " + major)
  override val school = "ustc"
  override def toString = {"Student " + name}
}

object basic2{
  def main(args: Array[String]): Unit = {
    var p = new Person
    p name = "WangCheng"
    println((p name) + " " + (p age))

    var p2 = new Person2("Jxiaolun", 22)
    println(p2.name + p2.age)

    var p3 = new Person2("Wang", "male")
    println(p3.name + ":" + p3.age + ":" +   p3.gender)

    var p4 = new Student("WangYUAN", 33, "math");
    println(p4)
  }
}
```:

你可能感兴趣的:(scala学习1)