Help to understand, please.

public class Math { private String a; void method() { this.a = "Hello"; } } 

Here is the variable "a", I pass it the string "Hello". And there is

 public class Physics { void method1() { "и здесь мне нужно использовать переменную "а" String b = a + "world"; } } 

How to do it? When I create an object, I get a Null.

  • one
    “it writes me” - who is “it”? - Igor
  • and what to write in main? At a minimum, you need to create an instance of the Math class too .... - Alexey Shimansky

2 answers 2

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.

    First, you need to initialize the Math class, then call the method method , which will set the value to a . Now, it turns out that from the outside we do not have access to the a field, for this the get_a() method is created, which returns a

     public class Math { private String a; public String get_a() { return this.a; } public void method() { this.a = "Hello"; } } public class Physics { public void method1() { Math a = new Math(); a.method(); String b = a.get_a() + "world"; } }