When you use the method1 method of the Physics class, then at least you create an instance of the specified class through the operator new and access its method ((!!!) unless the method is static).
Accordingly, the same should apply to the class Math and its method method . Or, at a minimum, pass new Math() as a parameter to the method (if this instance is later not needed).
For when you write String b = a + "world"; , it means that there is an attempt to access the variable a within this class itself (Physics). And since it is not, then the error.
public class Math { private String a; void method() { a = "Hello"; } public String getA() { return a; } } public class Physics { void method1(Math math) { String b = math.getA() + "world"; // System.out.print(b); } }
the main method may look like this:
new Physics().method1(new Math());
or
Math math = new Math(); Physics physX = new Physics(); physX.method1(math);
Why does it seem to me that it is better to transfer an object rather than create an instance of it directly in method1 ? Because there may be, for example, heirs from the class Math and you want to call their implementation of the method method , which will be different from the parent. Nor will you have to constantly rewrite the method method1 and write various conditions on objects of different types.