zoukankan      html  css  js  c++  java
  • scala对象简单记录

    object Person {
    
      private val eyeNum = 2
    
      def getEyeNum = eyeNum
    
      def main(args: Array[String]): Unit = {
        println(Person.getEyeNum)  // 2
      }
    
    }
    

      

    abstract class Hello(var message:String) {
    
      def sayHello(name :String)
    
    }
    
    object HelloImpl extends Hello("hello"){
    
      override def sayHello(name: String): Unit = {
        println(message + "," + name)
      }
    
    
      def main(args: Array[String]): Unit = {
        HelloImpl.sayHello("yxj")
      }
    
    }
    

      

    /**
      * 一个类和一个object对象名字相同,都在一个.scala文件中,那么他们就是伴生类和伴生对象
      *
      * @param name
      * @param age
      */
    class People(name:String , age:Int ) {
    
      def sayHello = println("hi," + name +", your age is " + age + ",your eyeNum is " + People.eyeNum)
    
    }
    
    object People {
    
      private val eyeNum = 2
    
      def getEyeNum = eyeNum
    
    }
    
    object objectsTest{
    
      def main(args: Array[String]): Unit = {
        val yy = new People("yxj" , 30)
        yy.sayHello
      }
    
    }
    

      

    /**
      * object中apply方法的使用,简化对象创建的过程
      *
      */
    
    class Apple(name:String ,age:Int) {
      println(name + "," + age)
    }
    
    object Apple{
    
      // 伴生对象的apply简化了创建伴生类的方式
      def apply(name: String, age: Int): Apple = new Apple(name, age)
    
      def main(args: Array[String]): Unit = {
        val a = Apple("yxj" , 30)
        println(a)
    
        // 普通的创建类的过程
        val a1 = new Apple("yxj" , 31)
        // 伴生对象定义了apply后,不需要在使用new关键字来创建一个类的对象实例了
    
      }
    
    }
    

      

  • 相关阅读:
    【博弈论】囚徒困境
    【LTE与5G】
    【现代通信技术】绪论
    【操作系统】 逻辑结构
    【密码学】
    【计算机网络】网络应用
    部署docker仓库-Harbor
    ELK+filebeat收集K8S平台日志
    istio-http流量管理
    K8S集群部署istio
  • 原文地址:https://www.cnblogs.com/yxj0728/p/9281809.html
Copyright © 2011-2022 走看看