在 Companion Object 中,如何直接访问类的私有方法和变量
时间: 2024-03-14 18:47:09 浏览: 24
在 Companion Object 中,可以直接访问类的私有方法和变量,但是需要注意以下两点:
1. 不能使用 `private` 修饰符,需要使用 `internal` 或 `protected` 修饰符;
2. 在访问时需要使用 `this` 关键字。
下面是一个示例代码:
```kotlin
class MyClass {
private val myPrivateVar = "Private Variable"
private fun myPrivateFun() {
println("Private Function")
}
companion object {
fun myFunction() {
val obj = MyClass()
println(obj.myPrivateVar)
obj.myPrivateFun()
}
}
}
fun main() {
MyClass.myFunction() // 输出: Private Variable\nPrivate Function
}
```
在这个示例中,`MyClass` 中定义了一个私有变量 `myPrivateVar` 和一个私有方法 `myPrivateFun()`。在 `Companion Object` 中,我们通过创建 `MyClass` 的实例来访问这些私有成员,然后调用相应的方法。
需要注意,我们在 `myFunction()` 中访问 `myPrivateVar` 和 `myPrivateFun()` 时,使用的是 `obj.` 前缀,表示访问的是 `obj` 对象的成员。因此,需要先创建 `MyClass` 的实例才能访问私有成员。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)