13 private關(guān)鍵字總結(jié)
修飾class
1、在class前面使用private可以被相同包(包含遞歸子包)訪問(能引入類);
2、在class前面使用private[包名]代表是包的訪問權(quán)限,只能指定的包名和子包(包含遞歸子包)下才能訪問;
private修飾 主構(gòu)造器、主構(gòu)造器參數(shù)、輔助構(gòu)造器、屬性、方法, 當前類和伴生對象可以訪問,其他對象不能訪問;
private[this]修飾 主構(gòu)造器、主構(gòu)造器參數(shù)、輔助構(gòu)造器、屬性、方法, 只有當前類可以訪問;
private[包名] 修飾 主構(gòu)造器、主構(gòu)造器參數(shù)、輔助構(gòu)造器、屬性、方法, 指定包名及子包可訪問。
示例:
在class前面使用private可以被相同包(包含遞歸子包)訪問(能引入類);
子包可引入
其他包不能引入
在class前面使用private[包名]代表是包的訪問權(quán)限,只能指定的包名和子包(包含遞歸子包)下才能訪問;
package day03// private[this] 修飾的主構(gòu)造器,伴生對象和其他對象都不可訪問class PrivateDemo2 private[this] (val name:String) { var age:Int = _// private[包名] 修飾的輔助構(gòu)造器,同包名或遞歸子包都可訪問 private[day03] def this(name:String, age:Int ) = { this(name) this.age = age }}object PrivateDemo2{ def main(args: Array[String]): Unit = {// val demo = new PrivateDemo2("hainiu") val demo = new PrivateDemo2("hainiu", 10) }}object privateDemo2Other{ def main(args: Array[String]): Unit = {// val demo = new PrivateDemo2("hainiu") val demo = new PrivateDemo2("hainiu", 10) }}
海汼部落原創(chuàng)文章,原文鏈接:(hainiubl/topics/75745)