W3docs

accessing a variable from another class

To access a variable from another class in Java, you can use the following steps:

To access a variable from another class in Java, you can use the following steps:

  1. Declare the variable as public or protected. public allows access from any class, while protected restricts access to the same package or subclasses.
  2. Create an instance of the class that contains the variable.
  3. Use the instance to access the variable.

Here is an example of how you can access a variable from another class:


public class ClassA {
    public int x = 10;
}

public class ClassB {
    public static void main(String[] args) {
        // Create an instance of ClassA
        ClassA a = new ClassA();

        // Access the variable x from ClassA
        int y = a.x;

        // Print the value of y
        System.out.println(y);
    }
}

Note: In Java, each public class must be defined in its own file (e.g., ClassA.java and ClassB.java).

This code defines a class, ClassA, with a public variable, x. It then defines a second class, ClassB, which creates an instance of ClassA and uses it to access the variable x. The value of x is then printed to the console.

Note that you can also access a static variable from another class using the class name, without creating an instance of the class. For example:


public class ClassA {
    public static int x = 10;
}

public class ClassB {
    public static void main(String[] args) {
        // Access the static variable x from ClassA
        int y = ClassA.x;

        // Print the value of y
        System.out.println(y);
    }
}

This code defines a static variable, x, in ClassA and accesses it from ClassB using the class name.

Best Practice: For better encapsulation, it is recommended to declare variables as private and provide public getter and setter methods instead of exposing them directly.