Scala_5.类和对象
发布日期:2021-05-07 00:19:23 浏览次数:31 分类:原创文章

本文共 1500 字,大约阅读时间需要 5 分钟。

Scala_5.类和对象

package com.lius/** * 类和对象 */object ClassAndObject{  /**   * 创建Point类   * @param xc 类参数   * @param yc 类参数   */  class Point(xc:Int,yc:Int){    var x :Int = xc    var y :Int = yc    def move(dx:Int,dy:Int): Unit ={      x += dx      y += dy      println(s"x的坐标点:${x}")      println(s"y的坐标点:${y}")    }  }  /**   * 创建继承与Point的Location类   * @param xc 类参数   * @param yc 类参数   * @param zc 类参数   */  class Location(val xc:Int,val yc:Int,val zc:Int) extends Point(xc,yc) {    var z: Int = zc    def move(dx: Int, dy: Int,dz:Int): Unit = {      x += dx      y += dy      z += dz      println(s"x的坐标点:${x}")      println(s"y的坐标点:${y}")      println(s"z的坐标点:${z}")    }  }  /**   * 创建Person类重写toString方法   * override def toString = {...}   */  class Person{    var name =""    override def toString = s"${getClass.getSimpleName}[name=${name}]"  }  /**   * 创建基于Person类的Employee类重写toString方法   * override def toString = {...}   */  class Employee extends Person {    var salary = 0.0    override def toString = s"${getClass.getSimpleName}[name=${name},salary=${salary}]"  }  def main(args: Array[String]): Unit = {    //利用类生成对象    val pt = new Point(10,20)    //调用对象move函数    pt.move(10,10)    //继承    """      1.重写非抽象方法必须用override修饰      2.只有在主构造函数才可以往基类的构造函数里写参数      3.在子类中重写超类抽象方法,不需要使用override关键字      |""".stripMargin    var loc =  new Location(10,20,5)    loc.move(10,10,5)    //override重写toString    var fred = new Employee    fred.name = "Fred"    fred.salary = 5000000    println(fred)  }}

 

上一篇:Scala_6.抽象函数Trait
下一篇:Scala_4.模式匹配

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年03月24日 07时14分32秒