Access Variable from subclass outside package
Here we will see how variables different access modifiers behave when they are access from a class outside same package
package com.accessmodifier;
/*
* Here we will learn to access variables with different access modifiers from other class in same package
*/
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 subclass 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 extends
AccessVariableFromAnotherClass {
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 below. 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);
/*
* As we have mentioned above that protected modifier treats sub class
* with special priority hence protected variable which can not be
* directly accessed(As shown above) still can be accessed via
* inheritance.
*/
/*
* Now we will create object of subclass 'class2' and will try to access
* again all those variables with different access modifiers. Note*: Now
* Protected variable(k) can also be accessed, which was not accessible
* in previous scenario. Still Private & Default variable will not be
* accessible from here. Hence compiler will show same error
* @line 45, 47
*/
AccessVariableFromAnotherClassDiffPkg class2 = new AccessVariableFromAnotherClassDiffPkg();
System.out.println(class2.i);
System.out.println(class2.j);
System.out.println(class2.k);
System.out.println(class2.l);
}
}
Trackback from your site.
