FAISAL
FAISAL

Reputation: 459

Set and Get static variables values through static method in different classes in java

Lets say I have 3 Classes: A, Data, and B

I pass a variable from class A which sets that passed variable to a public static variable in class Data with Data's class method setData() and trying to get the same value (which i was assigned in class A) in class B using Data's class method getData().

methods in Data class are public and static

public class Data{

public static string nameD;

public static void setData(String name){ nameD = name; }

public static String getData(){ return nameD; }

}

public class A{

String nameA="Test";

Data.setData(nameA); }

public class B{

String nameB; nameB = Data.getData(); println(nameB); }

But gives null string in class B.

How can i do that.?

Upvotes: 0

Views: 8281

Answers (3)

Mina Tadros
Mina Tadros

Reputation: 634

just call first class A to set the value for class Data then call class B to get the value inside the data.

ex:

public class A{
     String nameA="Test";
     public A() {
         Data.setData(nameA);
     }
 }

 public class B{
      String nameB; 
      B() {
         nameB = Data.getData(); 
         System.out.println(nameB); 

      }
 }

 public class Data{

    public static String nameD;

    public static void setData(String name){ nameD = name; }

    public static String getData(){ return nameD; }
  }

then if u made the following, you will got ur value new A(); new B();

Upvotes: 1

syntaxerror
syntaxerror

Reputation: 106

It's not valid code, because you cannot execute a statement like Data.setData() outside of any method.

If you put this code in a method inside class A and then call this method in your main program in the correct order (before calling getData()), it will still be very confusing code, but you should get your desired result.

Upvotes: 0

Peter_James
Peter_James

Reputation: 647

You could pass the object and have a static field in the object you pass.

Upvotes: 0

Related Questions