Small problem where the IDE doesn’t recognize when a variable is passed from one class to another in Java

Issue

Doing a little test in Java: In a class called A, I created a simple variable called name, setting “John” as value:

String name  "John";

In class B, I want this variable to be identified. So even writing the complete package import from class A in class B, and even writing in class B:

A.name;

The IDE is unable to identify the variable name in the class A.

The IDE is Android Studio, and it’s an Android application that already has the AppCompatActivity extends, and doesn’t allow multiple inheritance.

Solution

For that to work, to you need to declare the variable as

  • static so that you can access it without an instance of A (which is what you are trying to do)
  • public in case that B is in a different package

…making the line look like this:

public static String name  "John";

Answered By – f1sh

Leave a Comment