包及其导入

43 阅读1分钟

  • 1.package
  • 2.类似于文件夹
  • 3.在某个包下面新建的文件,会自动在开头部分添加package说明
  • 4.在不同的包之间,移动文件,也能自动更新头部的package说明
package tools

class student {
 def test():Unit={
   println("test...")
 }
}

屏幕截图 2025-11-27 091346.png

导入包(import)

把别的包下的资源(其他文件夹下的文件)导入到当前文件中使用

  1. 导入一个类 import tools.A
  2. 导入多个 import tools.{B, C, Student}
  3. 导入一个包下所有的类 包括... import tools._ /* 导入 tools 之下所有类、特质等 (包含子包,但需显式引用子包路径) */
  4. 导入子包里面的类 给类重命名(避免冲突)
package tools

object demo02 {

}
// 1. 导入一个类
// import tools.A

// 2. 导入多个
// import tools.{B, C, Student}

// 3. 导入一个包下所有的类 包括...
import tools._
/* 导入 tools 之下所有类、特质等
   (包含子包,但需显式引用子包路径) */

// 4. 导入子包里面的类 给类重命名(避免冲突)
import level01.Base34.{Student => NewStudent}

object demo2 {
  def main(args: Array[String]): Unit = {
    new A()
    new B()
    new C()

    val s1 = new NewStudent()
    s1.test()
  }
}