scala中类的简单使用记录

import scala.collection.mutable.ArrayBuffer

/**
  * scala 中内部类的使用
  */
class Classes {

  class Stu(name:String , age:Int) {}
  val stus = new ArrayBuffer[Stu]
  def getStu(name:String) = {
    new Stu(name , 0)
  }
}

object ClazTest{

  def main(args: Array[String]): Unit = {
    // 需要注意
    val c1 = new Classes
    val stu1 =c1.getStu("yxj")
    c1.stus += stu1

    println(stu1)

    val c2 = new Classes
    val stu2 = c2.getStu("yxj")
    c2.stus += stu2

    println(stu2)
    // 下面将类stu1添加到c2中是不允许的,会报错
    // c2.stus += stu1
    // 他们toString时打印的hashcode是不同的
    // classes.Classes$Stu@5c7fa833
    //classes.Classes$Stu@39aeed2f

  }

}

  

 

/**
  * scala 中类的使用
  */
class HelloWorld {

  var sex = ""

  private var name = "yxj"
  def sayHello(): Unit ={
    println("hello " + name)
  }

  def getName = name

}



object HelloTest {

  def main(args: Array[String]): Unit = {
    val hello = new HelloWorld
    hello.sayHello()

    hello.sex = "male";
    println(hello.sex)



    val s1 = new Student
    s1.age = 30
    val s2 = new Student
    s2.age = 20
    println(s1.older(s2)) // 返回true

    // 使用 private[this] myage 只能在本类中使用,


  }

}

  

class Student {

  private var myAge = 0

  def age_=(newAge : Int): Unit ={
    if(newAge > myAge) myAge = newAge
    else println("illegal age!!!")
  }

  def age = myAge

  def older(s : Student) = {
    myAge > s.myAge
  }
  
}

  

 

import scala.beans.BeanProperty

class LikeJavaClaz {
  @BeanProperty var name = ""
  
}



object LikeJavaClazTest {

  def main(args: Array[String]): Unit = {
    val likeJavaClaz = new LikeJavaClaz
    likeJavaClaz.setName("yexj")

    println(likeJavaClaz.name)
    println(likeJavaClaz.getName)


  }

}

  

posted @ 2018-07-08 23:37  小叶啊  阅读(504)  评论(0编辑  收藏  举报