Scala对象和类
package scala.zpark
//new关键字创建一个类,定义了两个变量x,y,一个方法move,xc,yc称为类参数,类参数在整个类中都可以访问
class lianxi1(xc:Int,yc:Int){
var x:Int = xc
var y:Int = yc
def move(dx:Int,dy:Int){
x = x + dx
y = y + dy
println("x的坐标为%d")
println("y的坐标为%d")
}
}
//使用 new 来实例化类,并访问类中的方法和变量:
object Test{
def main(args: Array[String]): Unit = {
def point = new point(xc=30,yc=20)
//移到一个新的位置
point.move(dx=5,dy=10)
}
}
运行结果:
Scala继承:scala用extends继承一个父类lianxi1,父类lianxi1也称为基类
package scala.zpark
//new关键字创建一个类,定义了两个变量x,y,一个方法move,xc,yc称为类参数,类参数在整个类中都可以访问
class lianxi1(val xc:Int,val yc:Int){
var x:Int = xc
var y:Int = yc
def move(dx:Int,dy:Int){
x = x + dx
y = y + dy
println("x的坐标为%d")
println("y的坐标为%d")
}
}
//使用 new 来实例化类,并访问类中的方法和变量:
object Test{
def main(args: Array[String]): Unit = {
def point = new point(xc=30,yc=20)
//移到一个新的位置
point.move(dx=5,dy=10)
}
}
//var 变量
//val常量
//定义父类变量只能用val来继承,重写抽象方法必须使用override修饰符修饰
class Location(override val xc:Int, override val yc:Int, val zc:Int)extends lianxi1(xc,yc){
var z = zc
def move(dx: Int, dy: Int,dz:Int):Unit = {
x = x + dx
y = y + dy
z = z + dz
printf("x的坐标是%d,y的坐标是%d,z的坐标是%d",x,y,z)
}
}
//在子类中重写超类的抽象方法时,不需要使用override关键字
object testtwo{
def main(args: Array[String]): Unit = {
val location = new Location(xc=12,yc=34,zc=34)
location.move(dx=5,dy=6,dz=5)
}
}
Scala重写一个非抽象方法,必须用override修饰符。
class Person{
var name = " "
override def toString = getClass.getName + "[name=" + name +"]"
}
class hahaha extends Person{
var salary = 0.0
override def toString: String = super.toString+"[salary="+salary+"]"
}
object testthree {
def main(args: Array[String]): Unit = {
val hahaha = new hahaha
hahaha.name = "zzx"
hahaha.salary = 30000
println(hahaha)
}
}
运行结果:
单例对象实例
class point(val xc:Int,val yc:Int){
var x:Int = xc
var y:Int = yc
def move(dx:Int,dy:Int): Unit ={
x = x + dx
y = y + dy
}
}
object Test{
def main(args: Array[String]): Unit = {
val point1 = new point(10,20)
printpoint
def printpoint{
println ("x的坐标是"+point1.x)
println("y的坐标是"+point1.y)
}}
}
运行结果:
伴生对象实例
//伴生对象实例
class Maker private(val color:String){
println("创建:" + this)
override def toString: String = "颜色" + color
}
// 伴生对象,与类名字相同,可以访问类的私有属性和方法
object Maker{
private val makers:Map[String,Maker] = Map(
"red" -> new Maker("red"),
"blue" -> new Maker("blue"),
"green" -> new Maker("green")
)
def getMaker(color:String) = {
if (makers.contains(color)) makers(color)else null
}
def apply(color: String) = {
if (makers.contains(color))makers(color) else null
}
def main(args: Array[String]): Unit = {
println(Maker("red"))
//单例函数调用,省略了.符号
println(Maker getMaker "blue")
}
}
运行结果为: