Home  >  Article  >  Java  >  Where are the private members of a class accessible?

Where are the private members of a class accessible?

(*-*)浩
(*-*)浩Original
2019-07-26 09:26:337660browse

Private members of the class can be accessed in the member functions of this class. Private members of a class are hidden in the derived class and can only be accessed from member functions of the base class.

Where are the private members of a class accessible?

Private members in Java are modified using private. (Recommended learning: Java Video Tutorial)

Private members can only be called in this class and cannot be seen outside this class. If you want to obtain private member variables in other classes, you can write a public get method in this class, and other classes can obtain private member variables by calling this get method.

class PrivateTest{
    private String str = "私有成员变量";
    //如果加上这个方法
    public String getStr(){
        return str;
    }
    public static void main(String[] args){
        System.out.println(str);//这里可以调用到str变量
    }
}
class OtherClass{
    public static void main(String[] args){
        PrivateTest pt = new PrivateTest();
        //String tryToGet = pt.str;//这句编译会报错,str不可见
        String getStr = pt.getStr();//这样 就可以获取到str的
    }
}

For more Java-related technical articles, please visit the Java Development Tutorial column to learn!

The above is the detailed content of Where are the private members of a class accessible?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn