kotlin 封装_Kotlin程序| 封装级别的各种可见性修改器的示例

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,

    可见性修改器有四种类型,

    1. Public
    2. Private
    3. Protected
    4. 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,

    函数,属性以及类,对象和接口可以在“顶层”上声明,即直接在包中声明,

    1. public: Visible everywhere, The default visibility, if there is not an explicit modifierpublic :在任何地方都可见,默认可见性,如果没有显式修饰符
    2. private: Visible inside the file containing the declaration.private :在包含声明的文件内部可见。
    3. internal: Visible everywhere with the same module.内部 :使用相同模块在任何地方都可见。
    4. 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 封装

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值