English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this article, you will learn about the 4 visibility modifiers in Kotlin and how they work in different situations.
Visibility modifiers are keywords used to set the visibility (accessibility) of classes, objects, interfaces, constructors, functions, properties, and their setters. (Visibility modifiers cannot be set for getters, as they always have the same visibility as the property)
Inالصفات والأشياء في KotlinIn the article, you briefly learned about the visibility modifiers public and private. In this article, you will learn in detail about the other two visibility modifiers protected and internal (as well as public and private).
A package organizes a set of related functions, properties, and classes, objects, and interfaces.
معدل | وصف |
---|---|
public | Visible anywhere |
private | Visible within the file containing the declaration |
internal | Visible within the same module (a group of Kotlin files compiled together) |
protected | Not applicable to packages (used for subclasses) |
ملاحظة:If the visibility modifier is not specified, the default value is public by default.
لنأخذ مثالاً:
// File name: hello.kt package test fun function1() {} // By default, it is public and visible anywhere private fun function2() {} // مرئي داخل hello.kt internal fun function3() {} // مرئي في نفس البند var name = "Foo" // مرئي في كل مكان get() = field // مرئي داخل hello.kt (مثل خصيصة نفسها) private set(value) { // مرئي داخل hello.kt field = value {} private class class1 {} // مرئي داخل hello.kt
هنا كيف تعمل تعديلات التوفر على الأعضاء المعلنة داخل الفئة (الوظائف، الخصائص):
معدل | وصف |
---|---|
public | مرئي للعميل الذي يمكنه رؤية الفئة المعلنة |
private | مرئي فقط داخل الفئة |
protected | مرئي داخل الفئة وأبنائها |
internal | كل العناصر التي يمكن رؤيتها في البند للعميل يمكنها رؤية الفئة المعلنة |
ملاحظة:إذا قمت بتعديل العضو protected في فئة الفرعية دون تحديد قابلية الوصول، فإن قابلية الوصول ستكون protected أيضًا.
لنأخذ مثالاً:
open class Base() { var a = 1 // عام بشكل افتراضي private var b = 2 // خاص بالفئة Base protected open val c = 3 // مرئي للفئة Base و Derived internal val d = 4 // مرئي في نفس البند protected fun e() {} // مرئي للفئة Base و Derived {} class Derived: Base() { // a, c, d و e()Base جميع الخصائص في فئة Base مرئية // b غير مرئي override val c = 9 // c هو protected {} fun main(args: Array<String>) { val base = Base() //base.a و base.d مرئي // base.b, base.c و base.e() غير مرئي val derived = Derived() // derived.c غير مرئي {}
بافتراض، توفر المُهندس هو عام. ولكن يمكنك تغييره. لذلك، تحتاج إلى إضافة كلمة المفتاح constructor.
في المثال التالي، المُهندس هو افتراضيًا عامًا:
class Test(val a: Int) { // كود {}
يمكنك تعديل توفره عبر الطريقة التالية.
class Test private constructor(val a: Int) { // كود {}
المُهندس هنا هو خاص.
ملاحظة: في Kotlin، لا يمكن للوظائف، المتغيرات والصفات أن تحتوي على مُعدل التوفر.