私人可见性修饰符的含义 [英] Meaning of the Private visibility modifier

查看:47
本文介绍了私人可见性修饰符的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的"Tosee"类中,当我调用s.hiddenInt时,hiddenInt是可见的.但是,当我在另一个类"CantSee"中创建"ToSee"对象时,私有变量不可见.为什么会这样呢?我的印象是,私有意味着在类的任何实例中,客户端都看不到那个特定的实例变量或方法?为什么然后我可以在"ToSee"的主要方法中看到hiddenInt?

In the class 'Tosee' below, hiddenInt is visible when I call s.hiddenInt. However, when I create a "ToSee" object in another class, 'CantSee', the private variable isn't visible. Why is this so? I was under the impression that private means that in any instance of a class, the client cant see that particular instance variable or method? Why then am I able to see hiddenInt in the main method of 'ToSee'?

public class ToSee {

    private int hiddenInt = 5;

    public static void main(String[] args) {
        ToSee s = new ToSee();
        System.out.println(s.hiddenInt);

    }
}


public class CantSee {

    public static void main(String[] args) {
        ToSee s = new ToSee();
        System.out.println(s.hiddenInt);
    }

}

推荐答案

Java中的私有表示仅在声明了该变量或方法的类中可以访问该变量或方法.如果您对私人的印象是真实的,那么它将永远无法使用.

Private in Java means the variable or method is only accessible within the class where it is declared. If your impression about private was true, it will not be accessible anywhere ever which makes it completely useless.

这篇关于私人可见性修饰符的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆