Pregunta

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?

¿Fue útil?

Solución

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.

Otros consejos

The problem is easy. You have the variable "i" to private, you need a pojo (get y set) public to use the variable "i".

For example :



    public int getI() {
       return this.i;
    }


In the implementation use :



    objBase.getI();


PDT: Sorry for my english I speek Spanish

BaseDemo is not an instance of Base, but even if it was a child of Base you've marked the field i as private. Only the class Base can access it, that's what private means. If it were protected then instances of Base or sub-classes of Base could access it.

i is private property in class Base so you can't access directly.This one of object oriented programming concepts.

You can create getter for it

In base class

public int getI(){
    return this.i
}

In BaseDemo you can call it

 System.out.println(objBase.getI());

private methods and variables have access only with in the class. Not out side the class, even you create instance you cannot access them.

From official docs

The private modifier specifies that the member can only be accessed in its own class.

You may want to define a getter method to access your variable outside the class BaseDemo.

public int getI(){
   return i;
}

Maybe this will be useful for you:

et cetera.

the error is because your are voilanting the rules of access specifiers, private access specifier is used to make your variables accessable just with in the same calss

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top