32 阅读1分钟

包的基本使用

基本步骤:创建包 → 创建对象(类) → 导入类

示例:

1. 创建包。右键,新建软件包。名称小写。

2. 在包上右键,新建类

3. 在测试文件中引入类,使用。

image.png

image.png

package jhart
// package 包
class Student {
  println("student....")

}
package jhart

object Main {
   def main(array: Array[Student]): Unit = {
     new Student()
   }
}

// 导入import

// 包名 类名

package art
// 导入import
// 包名 类名
import jhart.Student

object Main {
  def main(args: Array[String]): Unit = {
    new Student()
  }
}

导入包

// 1. import 导入一个类, 包名.类名

// 2. import 导入多个类, 包名.{类名1, 类名2}

// 3. import 导入包下边的所有的类 包名.*

package toolTest

//import tools.A, B, C;
import tools._

// 1. import 导入一个类, 包名.类名
// 2. import 导入多个类, 包名.{类名1, 类名2}
// 3. import 导入包下边的所有的类 包名.*

//import tools.A
//import tools.B
object Main {
  def main(args: Array[String]): Unit = {
    new A()
    new B()
    new C()
  }
}

如果导入的一个类,与现有的类名有冲突? 包名.{类名 => 新名字}

导入的时候,可以取个新名字重命名

package toolTest
// import tools.A, B, C;
// import tools._
// 1. import 导入一个类  包名.类名
// 2. import 导入多个类  包名.{类名1, 类名2}
// 3. import 导入包下边的所有的类 包名._
// 4. 如果导入的一个类,与现有的类名有冲突? 包名.{类名 => 新名字}
// 导入的时候,可以取个新名字  重命名
import tools.{C => C1}
//import tools.A
//import tools.B
class C() {
  println("C")
}
object Main{
  def main(args: Array[String]): Unit = {
    new C1()
    new C()
  }
}