Access Variable from other class in same package
Here we will learn to access variables with different access modifiers from other class in 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;
}
class AnotherClass {
// Here we will access variable of above class with different AM
public static void main(String args[]) {
AccessVariableFromAnotherClass class1 = new AccessVariableFromAnotherClass();
/*
* Variables with different access modifiers can be accessed except
* Private variable as it is not visible outside class. Hence Line 25
* will have compile time error
* "The field AccessVariableFromAnotherClass.j is not visible"
*/
System.out.println("Value of public variable" + class1.i);
System.out.println("Value of private variable" + class1.j);
System.out.println("Value of protected variable" + class1.k);
System.out.println("Value of Default variable" + class1.l);
}
}
Trackback from your site.

Comments (1)
Java Beginners Tutorial Java access modifiers examples
| #
[...] Access Variable(Public, Private, Protected & Default) from another class within Package. [...]
Reply