Home »
Java programs
Java program to access variable from another class
In this java program, we are going to learn how to access variable from another class? Here is an example that is accessing variable from another class in java.
Submitted by Preeti Jain, on March 17, 2018
Here, we are using the concept of behavior of instance variable, static variable and final variable how variable is accessible inside static function?
Access variable from another class in java
class AccessVariableFromAnotherClass{
int a = 10;
static int b = 20;
final int c = 30;
public static void main(String[] args){}
}
public class MainMethodClassForAcessVariable{
public static void main(String[] args){
AccessVariableFromAnotherClass avfac = new AccessVariableFromAnotherClass();
/* Instance variable can access with object */
System.out.println("Access Instance Variable like this :"+avfac.a);
/* we can access static variable from two types */
/* 1. we can access static variable with the help of object */
System.out.println("Access Static Variable like this :" +" " +avfac.b);
/* 2. we can access static variable with the help of classname */
System.out.println("Access Static Variable like this :" +" " +AccessVariableFromAnotherClass.b);
/* we cannot access static variable directly */
//System.out.println(b);
/* we can access final variable with object */
System.out.println("Access Final Variable like this :" +" " +avfac.c);
/* we cannot access final variable directly */
//System.out.println(c);
}
}
Output
Access Instance Variable like this :10
Access Static Variable like this : 20
Access Static Variable like this : 20
Access Final Variable like this : 30