• 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)
    
    
      }
    
    }
    

      

  • 相关阅读:
    【oracle】查看表空间对应文件所在位置
    【oracle】查看表空间信息
    【java异常】java.lang.Integer cannot be cast to java.lang.String
    【oracle】DATE输出是什么东西
    数字万用表的精度和分辨率,ADC的位数
    二阶系统
    Verilog中实现电平检测
    模拟信号和数字信号,直流信号和交流信号
    噪声:强度,方差信噪比(待完善)
    Simulink模块之Band-Limited White Noise
  • 原文地址:https://www.cnblogs.com/yxj0728/p/9281801.html
Copyright © 2020-2023  润新知