Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
0
Accessibility of instance variables can be controlled with all the four access specifiers- public, private, protected and the default restriction (no access specifier mentioned). When a variable is declared as public, it can be modified from all classes in the same or different packages. When we talk of modification here, it refers to the modification of the variables corresponding to an object built out of this class and not the variable of the class itself. If no access specifier is stated, then these variables are accessible from classes in the same package only. If the variable is private, access is restricted to the class itself. If we create an object of this class in the main method of the same class, the variable is accessible but if the object is created in different class, the variable is accessible. Look at the following sample code for example. public class Student { private name; public static void main ( String[] args ) { Student s = new Student (); s.name = "Sai"; // allowed } } In the above program, we were able to modify the name variable directly even though the access specifier was private. This is because the variable was accessed from the same class itself. If we create an object of the Student class in a new class, such an StudentTest, access would be denied. public class StudentTest { public static void main ( String[] args ) { Student s = new Student (); s.name = "Sai"; // not allowed } }
21st Mar 2017, 8:26 PM
saeed
saeed - avatar