04 类与对象

在了解了scala的的基本语法和集合后,本节将阐述scala当中的类、对象与函数。

1 系统、软件以及前提约束

2 操作

  • 1 object
    在idea中创建一个Test.scala,这个就是所谓的静态类,加入以下内容:
//静态类
object Test {
  //静态入口方法
  def main(array:Array[String]): Unit ={
    //调用test无参方法
    test();
    //调用test无参方法
    test;
    //调用test有参方法
    test("ali")
    //调用test1无参方法
    test1;
  }
  //声明test无参方法,调用的时候有两种方式:test  , test()
  def test(): Unit ={
    println("test()")
  }
  //声明test有参方法,调用的时候有一种方式: test("ali")
  def test(name:String): Unit ={
    println(name)
  }
  //申明test1无参方法,可以省略小括号,调用的时候只有一种方式 test1
  def test1={
    println("test1")
  }
}
``
* 2 class
在idea中加入Student.scala,这是一个普通类,修改内容如下:

class Student {
val age = 9;
val name:String = "zhangli";
def test1(): Unit ={
println(age);
}

def test2(): Unit ={
println(name);
}
}

在idea中再次加入Object TestStudent.scala,修改内容如下:

object TestStudent {
def main(array:Array[String]): Unit ={
val student = new Student();
student.test1();
student.test2();
val student1 = new Student;
student1.test1;
student1.test2;
}
}

* 3 构造器
任何一个类都是有默认构造方法的,此方法与类名同名,可以不用显式的申明。无参的构造方法在调用的时候可以不用加小括号。在scala中构造函数分为主构造函数和辅助构造函数。

//定义一个类,默认包含主构造函数
class Time {
private var hr = 0
private var min = 0
//辅助构造函数,包含一个参数
def this (hr : Int) {
this () //调用主构造函数,必须调用
this.hr = hr
}
//辅助构造函数,包含两个参数
def this (hr : Int, min : Int) {
this (hr) //调用辅助构造函数,必须调用
this.min = min
}
}

* 4 apply
在scala命令行中执行以下语句:

class TestApply {
def apply(name:String): Unit ={
println("apply test : "+name)
}
}
//因为默认构造方法没有参数,所以可以不必加括号
val testApply = new TestApply
testApply.apply("ali")
//下面的语句与上面的语句等价,下面语句的写法就是隐式调用apply方法
testApply("ali")

* 5 update
在scala命令行中执行以下语句:

import scala.collection.mutable.Map
val user = Map("ali"->17,"xiaoli"->28)
user.update("ali",20)
//下面的语句等价于上面的语句,隐式调用update方法
user("ali")=6

* 6 value和value_
value以及value_类似于get以及set方法,如此调用更为简便。在scala命令行中执行以下语句:

//定义一个Student
class Student {
var age:Int = 9;
def value = age
def value_(newAge : Int){
age = newAge
}
}
//测试
object TestStudent1 {
def main(array:Array[String]){
val student = new Student1;
student.value_(18);
println(student.value)
}
}

以上就是在idea中创建scala类和使用类的过程。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值