Search code examples
javaobjectaccess-modifiers

Regarding access specifiers


I defined a Class Base

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

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);  
        }  
}  

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

I'm confused while coding, what is wrong?


Solution

  • See Controlling Access to Members of a Class:

    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
    

    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.