kotlin 封装
封装级别的各种可见性修改器 (Various Visibility Modifiers on Package Level)
Visibility modifiers are that set the accessibility (visibility) of Classes, objects, interfaces, constructors, functions, properties, and their setters.
可见性修改器用于设置类,对象,接口,构造函数,函数,属性及其设置器的可访问性(可见性)。
There are four types of visibility modifiers,
可见性修改器有四种类型,
- Public
- Private
- Protected
- Internal
Getters always have the same visibility as the properties.
吸气剂始终具有与属性相同的可见性。
Visibility Modifiers inside Packages:
封装内的可见性修饰符:
Functions, properties, and classes, objects and interfaces can be declared on the "top-level", i.e. directly inside a package,
函数,属性以及类,对象和接口可以在“顶层”上声明,即直接在包中声明,
- public: Visible everywhere, The default visibility, if there is not an explicit modifierpublic :在任何地方都可见,默认可见性,如果没有显式修饰符
- private: Visible inside the file containing the declaration.private :在包含声明的文件内部可见。
- internal: Visible everywhere with the same module.内部 :使用相同模块在任何地方都可见。
- protected: Not available for top-level declaration.protected :不适用于顶级声明。
Local variables, functions, and classes can not have visibility modifiers.
局部变量,函数和类不能具有可见性修饰符。
To specify the visibility of the primary constructor of a class, use the following syntax (by default constructors are public),
要指定类的主要构造函数的可见性,请使用以下语法(默认情况下,构造函数是公共的),
class C private constructor(a: Int) { ... }
该程序在Kotlin上演示包装级别的各种可见性修改器示例的示例 (Program to demonstrate the example of Example of various visibility modifiers on package level in Kotlin)
package com.includehelp
// Public by default, visible to everywhere
fun fun1(){
// local variable can not have visibility
var a=5
println("Inside Fun1 $a")
}
// private , visible inside Containing file
// VisibilityModifiersInsidePackages.kt
private fun fun2(){
println("Inside Fun2")
}
// internal , visible inside same module
internal fun fun3(){
println("Inside Fun3")
}
// public by default visible everywhere
var name="IncludeHelp"
// by default public, visible every where
class MyClass
// Main function, Entry point of program
fun main(){
// call function
fun1()
// call function
fun2()
// call function
fun3()
//Access variable
println("Name : $name")
}
Output:
输出:
Inside Fun1 5
Inside Fun2
Inside Fun3
Name : IncludeHelp
翻译自: https://www.includehelp.com/kotlin/example-of-various-visibility-modifiers-on-package-level.aspx
kotlin 封装