其他分享
首页 > 其他分享> > 寒假学习日报(三十八)

寒假学习日报(三十八)

作者:互联网

  今日学习:scala,英语

暂定内容,后续可能会有补充

scala类中的构造器运用:

package com.chapter01.classabout

object ConDemo01 {
  def main(args: Array[String]): Unit = {
    val p1 = new ConPerson("abc", 20)
    println(p1)
    println("================================")
    val p2 = new ConPerson("GOGOGO")
    println(p2)
    println("================================")
    val p3 = new ConA
    println("================================")
    //执行顺序为父类,子类非函数部分,子类辅助构造器部分
    val p4 = new ConA("K")
  }
}

//主构造器将非函数部分全部执行
class ConPerson(inName: String, inAge: Int) {
  var name: String = inName
  var age: Int = inAge

  //重写toString
  override def toString: String = {
    "name=" + this.name + "\t age=" + this.age
  }

  //辅助构造器
  def this(tname: String) {
    //第一行必须显式调用主构造器。
    this("null",0)
    this.name = tname
  }

  println("构造")
}

class ConB{
  println("ConB")
}

class ConA extends ConB{
  println("ConA()")
  def this(name:String){
    //之所以先显式调用主构造器,是为了保持与父类的联系,否则在调用辅助构造器时与ConB的关系会断掉,不符合逻辑
    this
    //super()会报错,辅助构造器中不允许直接调用父类
    println("ConA this")
  }
}

package com.chapter01.classabout

object ConDemo02 {
  def main(args: Array[String]): Unit = {
    val p1 = new Con2Person("KI")
    p1.showInfo()
  }
}

//主构造器私有化,此时只能通过辅助构造器来进行构造
class Con2Person private(){
  var name: String = _
  var age: Int = _

  //辅助构造器无论是直接还是间接,必须在第一行调用主构造器
  def this(name: String) {
    //直接调用
    this()
    this.name = name
  }

  //辅助构造器私有化
  private def this(name: String, age: Int) {
    //直接调用
    this()
    this.name = name
    this.age = age
  }

  def this(age: Int) {
    //间接调用:这里调用的是第一个辅助构造器:def this(name: String),其中调用了主构造器
    this("null")
    this.age = age
  }

  def showInfo(): Unit = {
    println("Person信息如下")
    println("name=" + this.name)
    println("age=" + this.age)
  }
}

package com.chapter01.classabout

object ConDemo03 {
  def main(args: Array[String]): Unit = {
    val w1 = new Worker("GO1")
    println(w1.name)
    val w2 = new Worker2("GO2")
    println("inName=" + w2.inName + "\t name=" + w2.name)
    val w3 = new Worker3("GO3")
    w3.inName = "Change3"
    println("inName=" + w3.inName + "\t name=" + w3.name)
  }
}
//主构造器是(inName:String),inName就是局部变量
class Worker(inName:String){
  var name = inName
}
//若使用val修饰,那么inName是Worker2的一个private的只读属性
class Worker2(val inName: String){
  var name = inName
}
//若使用var修饰,那么inName是Worker2的一个private的可读写属性
class Worker3(var inName: String){
  var name = inName
}

 

 scala中的get set方法

package com.chapter01.classabout

import scala.beans.BeanProperty

object BeanDemo {
  def main(args: Array[String]): Unit = {
    val b = new BeanTry
    b.name = "HAHA"
    println(b.name)
    //使用@BeanProperty自动生成的get set方法
    b.setName("GOGO")
    println(b.getName())
  }
}

class BeanTry {
  @BeanProperty var name: String = null
}

 

标签:name,三十八,日报,age,inName,寒假,println,def,String
来源: https://www.cnblogs.com/20183711PYD/p/14406498.html