How can Java access elements in other classes?

To access elements from another class, you need to use the access modifier and access methods of that element.

Assuming we have a class A with a private member variable and a public member method, we want to access that member variable and call that member method in another class B.

In class A, we need to use the private modifier to restrict access to the member variable, while also providing a public getter method to retrieve the value of that member variable.

public class A {
    private int memberVariable;

    public int getMemberVariable() {
        return memberVariable;
    }
}

In class B, we can instantiate an object and then retrieve the value of a member variable by calling the getter method of class A.

public class B {
    public static void main(String[] args) {
        A myObject = new A();
        int value = myObject.getMemberVariable();
        System.out.println(value);
    }
}

In this way, it is possible to access the member variables of class A in class B. Similarly, if class A has public member methods, we can also perform the corresponding operations by creating an object and calling that method.

bannerAds