Home >Java >javaTutorial >Introduction and understanding of java access permissions
The visible scope of global variables and methods in the class, that is, the scope that can appear through object references.
##public | protected | private | |
√ | √ | ##× | |
√ | × | ##× | Can it be inherited |
√ | ##√ | × | 3. Understanding of visibility |
The fact that a variable or method is not visible to a class does not mean that the variable or method cannot appear in class B, but it cannot be directly exposed in class B, but can be exposed indirectly. Appears indirectly through method references of public or protected types.
package com.javase.temp;import org.junit.Test;public class TempTest {private String str = new String("abc"); @Testpublic void printStr() { System.out.println(this.str); } }
Obviously there is a member variable str in the TempTest class, which is of private type and is not visible to other classes, which means that the variable cannot be referenced through an object. Forms appear in other classes and can appear indirectly in other classes by calling the printStr method.
package com.javase.temp;import org.junit.Test;public class TempTest01 { @Testpublic void test01() { TempTest obj = new TempTest(); obj.printStr();//通过TempTest类型的public类型的方法间接访问了private类型的变量,在访问时不知道private类型变量的情况 } }
Output:
##Call the TempTest object obj in the TempTest01 class The method printStr in printStr outputs the value of the private variable str. str is not directly exposed in TempTest01, but is directly exposed in the method printStr of TempTest, and the method printStr is directly exposed in TempTest, thus making str indirectly exposed in TempTest.
Although the value of the private type variable in TempTest is output in TempTest01, this output is random and unconscious. TempTest01 has no way of knowing that the output result comes from the variable str, and the output is meaningless. .A variable designed not to be directly accessed by the outside world is usually used as an intermediate process in this type of operation to assist other visible variables and methods.
The above is the detailed content of Introduction and understanding of java access permissions. For more information, please follow other related articles on the PHP Chinese website!