/**
* 第9章 包和引入
*/
//########################### 9.1 包 #################################
//Scala中的包并不要求目录和包之间的关联关系
package com {
package horstmann {
package impatient {
class Employee(id: Int) {
def description = "An employ with id " + id
}
}
}
}
//也支持同一文件下为多个包贡献内容
package com {
package shuai {
package module_09_import_package {
class Dog(name: String) {
def description = "Dog's name is " + name
}
}
}
}
//########################### 9.2 作用域 #################################
//串联式包语句
//包的作用域支持嵌套,包名是可以相对的
package com.horstman.impatient {
package animal {
//串联式包语句
class Cat(name: String) {
def description = "Dog's name is " + name
}
//包的作用域支持嵌套,包名是可以相对的
package people {
class Man(name: String) {
def description = "Dog's name is " + name
}
}
}
}
//########################### 9.3 包对象 #################################
/**
* 包可以包含类、对象、特质,但是不能包含函数和变量的定义,这个是Java虚拟机的限制
* 为了解决这个问题,每个包都有一把包对象.可以在包对象中定义这些函数和常量
*/
package com.lin {
//包对象 定义在父包
package object ye {
val defaultName = "xiao lin"
}
package ye {
class Shu() {
def description = "Dog's name is " + defaultName
}
}
object Aaa extends App {
val shu = new com.lin.ye.Shu
println(shu.description) //Dog's name is xiao lin
}
}
//########################### 9.4 包可见性 #################################
/**
* 可以通过private[包名]设置包的可见性
*/
package com.lin2 {
//包对象 定义在父包
package object ye2 {
val defaultName = "xiao lin"
}
package ye2 {
private[ye2] class Shu2() {
def description = "Dog's name is " + defaultName
}
object Bbb extends App {
val shu2 = new com.lin2.ye2.Shu2 //Yes
println(shu2.description)
}
}
}
//########################### 9.5 引入 #################################
/**
* scala中包的引入不限于文件顶部
*/
//########################### 9.6 重命名和隐藏方法 #################################
package com.lin2 {
//通过包选择器选择单个类
import java.awt.{Color, Font}
//重命名
import java.util.{HashMap => JavaHashMap}
//隐藏某个成员
import java.util.{HashSet => _, _}
import scala.collection.mutable._
object Ccc extends App {
println(Color.BLACK)
println(Font.BOLD)
val map = new JavaHashMap[String, String]()
map.put("aa", "bb");
println(map.toString)
new HashSet[String] //java.util.HashSet被隐藏
}
}