Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Access Control
Java Syntax Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Syntax Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java syntax.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
In Java, access control tells the program how much access a variable, class or method is given. Access control is important because it affects visibility based on different access control types. You may have noticed in prior topics the use of words such as public and private, which are examples of access control types. Take a look at the examples below.
AccessControlExample.java
package exlcode;
public class AccessControlExample {
public static void main(String[] args) {
// This will be explained in Unit 8
AccessControlTest accessControlTest = new AccessControlTest();
System.out.println(accessControlTest.exampleVariableOne);
System.out.println(accessControlTest.exampleVariableTwo);
// accessControlTest.exampleVariableThree will cause an error because
// exampleVariableThree is private
}
}
AccessControlTest.java
package exlcode;
public class AccessControlTest {
public static int exampleVariableOne = 5;
public static int exampleVariableTwo = 10;
private static int exampleVariableThree = 100;
}
When a variable's or method's access is not specified public or private, it will have default visibility. Default visibility is packaged private; it is visible to all classes in the same package. It is best to declare members public if that is the true intent. If an instance variable is declared private, it can only be used by the methods of that class. In the preceding example, AccessControlTest has its own private variable that is not accessible by the main method of the AccessControlExample class.
Access control allows other users to use your program without ever accessing, altering, or even knowing that the private variables or methods exist.