关于访问说明符 [英] Regarding access specifiers

查看:116
本文介绍了关于访问说明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个班级基础

class Base  
{  
    private int i;  
    Base(int i)  
    {  
        this.i = i;  
    }  
}  

因此基类的对象可以访问私有变量。 / p>

So object of Base class can access private variable.

class BaseDemo  
{  
        public static void main(String[] args)  
        {  
            Base objBase = new Base(10);  
            System.out.println(objBase.i);  
        }  
}  

但这给了我一个编译器错误,我可以私有访问在 Base 中。

But it's giving me a compiler error I has private access in Base.

编码时我很困惑,怎么了?

I'm confused while coding, what is wrong?

推荐答案

请参见控制对类成员的访问

Modifier    Class   Package Subclass    World
---------------------------------------------
public      Y      Y        Y           Y
protected   Y      Y        Y           N
no modifier Y      Y        N           N
private     Y      N        N           N

您应该使用 getter 。这就是封装的整个思想。您应该从外部隐藏实现,并提供设置器获取器

You should have a getter for that field. This is the whole idea of encapsulation. You should hide your implementation from outside and provide setters and getters.

这篇关于关于访问说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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