Regarding access specifiers

非 Y 不嫁゛ 提交于 2019-12-12 14:22:32

问题


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?


回答1:


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.




回答2:


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




回答3:


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.




回答4:


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



回答5:


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.




回答6:


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:

  • How do getters and setters work?
  • http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

et cetera.




回答7:


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



来源:https://stackoverflow.com/questions/20746444/regarding-access-specifiers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!