scala 中的 OOP总结(面向对象编程)

本文深入浅出地介绍了Scala语言的基础概念,包括类、对象、trait、构造函数、伴生对象、异常处理、模式匹配、Option使用、样例类及隐式转换。通过丰富的案例,如Person类、HelloTrait特质、模式匹配的使用等,帮助读者快速掌握Scala编程技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-1.class 类

    和 Java 中类是一样的

-2.Object 对象

    类比 和 Java 单例对象

    main 方法运行在此处

-3.trait

    类比 Java 中接口 Interface

隐式转换 implicit
implicit

    隐式的,隐藏的

        偷偷摸摸

    关键词:

        修饰 class,修饰 def, 修饰变量,修饰参数

 

案例 1:

/**
  *创建一个类
  *   -1.属性field,attribute:名词
  *   -2.方法method/函数function:动词
  */
class People {
 
  /**
    * 属性定义
    */
  //当属性使用var声明的时候,编译的时候,会生成Getter和setter方法
  var name:String = _
  //当属性使用val声明的时候,编译的时候,会生成Getter方法
  val age:Int = 17
 
  /**
    * 方法定义
    */
  def watchFootBall(teamName:String):Unit= {
    println(s"$name is watching match of $teamName")
  }
  def sayHello(name:String):String = {
    s"Hello $name"
  }
}
object SimpleObjectDemo {
  def main(args: Array[String]): Unit = {
    //创建一个对象
    val people = new People()
    //设置名称
    people.name = "huadian"
 
    //获取属性的值
    println(s"name is ${people.name}")
    println(s"age is ${people.age}")
 
    people.watchFootBall("Chelse")
    println(people.sayHello("laosun"))
  }
}
  * 在 Scala 中构造函数有 2 种
  *   构造函数的功能:在创建类的对象的时候,进行初始化操作
  * -1. 主构造函数
  *     只有一个
  *      直接 紧跟 在 类 class 后面,如果没有属性的话,可以省略()
  * -2. 附属构造函数
  *    可以有很多
  *
  *  一个.scala 文件中,一个类的名字和对象的名字一致,
  *   互为伴生对象和伴生类
  *   可以互相访问私有的属性和方法

//伴生类
class People(val name:String,val age:Int){
 
  var school:String = "huadian"
  private  val money:Double = 10000000.0
 
  //定义附属构造函数
  def this(_name:String,_age:Int,_school:String){
    //第一行必须调用主构造函数
    this(_name,_age)
    this.school = _school
    println(People.yaoshi)
  }
 
  def this(_name:String,_school:String){
    //第一行必须调用主构造函数
    this(_name,18)
    this.school = _school
  }
}
//伴生对象
object People{
  private  val yaoshi:String = "XXXX"
  def apply( name: String, age: Int): People = new People( name, age)
  def apply( name: String, age: Int,school:String): People = new People( name, age,school)
  def getMoney():Unit={
    println((new People("zs",11)).money)
  }
}
 

  * 定义一个 Trait,用于实现 与 人打招呼
  *
  * 和 Java 中 interface 一样

trait HelloTrait {
  def sayHello(name:String)
}
/**
  * 定义一个Trait,用于 交朋友
  */
trait MakeFriendsTrait {
  def makeFriends(people:People)
}
class People(val name:String) extends HelloTrait with MakeFriendsTrait {
  override def sayHello(name: String): Unit = {
    println(s"Hello $name")
  }
 
  override def makeFriends(people: People): Unit = {
    println(s"my name is $name ,you name is ${people.name}")
  }
}
object TraitDemo {
  def main(args: Array[String]): Unit = {
    val p1 = new People("xyy")
    val p2 = new People("小姐姐")
 
    p1.sayHello("小哥哥")
    p1.makeFriends(p2)
 
  }
}
异常地处理:

object ExceptionDemo {
  def main(args: Array[String]): Unit = {
    /**
      * Java 中异常处理
      *   try{
      *     ....
      *   }catch(Exception){
      *     ....
      *   }finally{
      *     ....
      *   }
      */
 
    try {
      val result = 1/"xx".toInt
    }catch {
      case e:Exception =>processException(e)
    }finally {
      println("finally..........")
    }
  }
 
  //根据不同异常的类型 进行不同的处理
  def processException(e:Exception): Unit ={
    e match {
      case e:ArithmeticException=>{
        println("ArithmeticException")
        e.printStackTrace()
      }
      case e:NumberFormatException=>{
        println("数字格式化错误")
        e.printStackTrace()
      }
      case e:Exception => e.printStackTrace()
    }
  }
}

模式匹配使用:

object PatternDemo {
  def main(args: Array[String]): Unit = {
    judgeGrade("F","zs")
    val list: List[(String, (String, Int))] =  List(("A",("a",1)),("B",("B",2)),("C",("c",3)))
    //获取List中int类型数据
    list.map(tuple => tuple._2._2)
    //使用模式匹配
    val xx: List[Int] = list.map{
      case (ip,(name,age)) =>age
    }
    val list2: List[Array[Any]] = List(Array("sz", 24, 34.98), Array("ls", 23, 90.09), Array("ww", 34, 12.89))
    list2.map{
      case Array(name,orderId,money) => money
    }
    val logInfo  = "zhangsan,34,male,177777"
    val Array(name,age,sex,telphone)  = logInfo.split(",")
    println(s"$name")
  }
  /**
    * 根据 学生的成绩(类别A,B,C,D)等级,给出不同的评语
    */
  def judgeGrade(grade:String):Unit ={
    grade match {
      case "A" =>println("excellent.......")
      case "B" =>println("good......")
      case "C" =>println("just so so ......")
      case _ =>println("you need to work hader")
    }
  }
  def judgeGrade(grade:String,name:String):Unit ={
    grade match {
      case "A" =>println("excellent.......")
      case "B" =>println("good......")
      case "C" =>println("just so so ......")
      case _grade if "zs".equals(name) =>println(s"just so so ${_grade}")
      case _ =>println("you need to work hader")
    }
  }
}


 

option 的使用:

  * Option 有 2 个子类
  *  -some
  *   表示有值
  *  -none
  *  表示无值

object OptionDemo {
  def main(args: Array[String]): Unit = {
    val map = Map("A"->1,"B"->2)
 
    val opt: Option[Int] = map.get("A")
    //val optValue = if(opt.isDefined){ opt.get}
    val optValue = if(opt.isDefined) opt.get
 
    val x: Int = map.get("A") match {
      case Some(value) =>value
      case None => 0
    }
    /**
      * def getOrElse[B1 >: B](key: A, default: => B1): B1 = get(key) match {
      * case Some(v) => v
      * case None => default
      * }
      */
    val xx = map.getOrElse("A",0)
  }
}
 

样例类:

case class AAA(name:String,age:Int)
 
//相当于下面这段代码
class AA(name:String,age:Int)
object AA{
  def apply(name: String, age: Int): AA = new AA(name, age)
}
 
class People
case class Student(name:String,classRoom:String) extends People
case class Teacher(name:String,subject:String) extends People
 
 
object caseClassDemo {
 
  def main(args: Array[String]): Unit = {
    val  aaa = AAA("zs",18)
 
    check(Teacher("xx","java"))
  }
 
  def check(people: People): Unit ={
    people match {
      case Teacher(name,subject)=>println("teacher")
      case Student(name,classRoom)=>println("Student")
      case _ =>println("==================")
    }
  }
}


 

隐式函数:

/**
  * 隐式函数
  * 可以让一个对象偷偷的变身
  * 变身函数:
  *     (0)变身函数被 implicit 修饰,函数名任意
  *     (1)变身函数一般在:伴生对象中
  */

 

//普通人
class Man(val name: String)
 
//object Man{
//  implicit def man2SuperMan(man:Man):SuperMan={
//    new SuperMan(man.name)
//  }
//}
 
object AAA{
  implicit def man2SuperMan(man:Man):SuperMan={
    new SuperMan(man.name)
  }
}
 
//超人:奥特曼
class SuperMan(val name: String){
  //发射激光
  def emitLaser():Unit= println("emit a laser.........")
}
 
 
object ImplicitDemo {
  def main(args: Array[String]): Unit = {
    val man = new Man("super")
 
    /**
      * 默认情况下:
      *   找变身函数 当前可见的作用域里面找,
      *         原类型伴生对象中找 (推荐用法)
      *         当前类下面找
      *         手动导入
      */
    import com.huadian.bigdata.oop.demo08.AAA._
    man.emitLaser()
  }
//  implicit def man2SuperMan(man:Man):SuperMan={
//    new SuperMan(man.name)
//  }
 
}


案例:

class SignPen{
  def write(name:String) = println(s"$name")
}
object SignPen{
   implicit val signPen:SignPen = new SignPen
}
 
 
object ImplicitParamDemo {
  def main(args: Array[String]): Unit = {
    signForMeetUp("ZS")
  }
 
  //参加某个技术交流沙龙,到达会场需要签字
  def signForMeetUp(name:String)(implicit signPen: SignPen):Unit={
    signPen.write(name)
  }
 
  def xxx(name:String)(age:Int)={
 
  }
}


 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值