Access Variable from class in different package
Here we will see how variables different access modifiers behave when they are access from a class outside same package
package com.accessmodifier;
public class AccessVariableFromAnotherClass {
// We will try to access below variable from other class
public int i;
private int j;
protected int k;
int l;
}
Access variable from above Class from a Class in different package.
package com.accessmodifier2;
import com.accessmodifier.AccessVariableFromAnotherClass;
/*
* Here we will see how variables different access modifiers behave when they are access from a
* class outside same package
*/
public class AccessVariableFromAnotherClassDiffPkg {
public static void main(String args[]) {
/*
* Now if we try to access all variable from class in different package.
* Only public variable is accessible. Private is not visible outside
* class hence it can not be accessed from here. Protected / Default is
* only visible to package hence can not be accessed outside package.
* Note *: Protected have special privilege for subclasses which we will
* see later. Because of all above reasons Compiler will show error
* "The field AccessVariableFromAnotherClass.k/i/j is not visible" for
* line no. 25, 26, 27
*/
AccessVariableFromAnotherClass class1 = new AccessVariableFromAnotherClass();
System.out.println("Value of public variable in class :" + class1.i);
System.out.println("Value of private variable in class :" + class1.j);
System.out.println("Value of protected variable in class :" + class1.k);
System.out.println("Value of default variable in class :" + class1.l);
}
}
Trackback from your site.
