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_5.类和对象
最新推荐文章于 2024-06-22 18:07:31 发布