Search code examples
javavariablesgetsetaccessor

How to set a variable in one class and get it in another


Once I have set the "set" method in one class to set my accessor, is it possible to return(get) that variable/string in another class without first having to "set" the variable again?

public class A {
Edits edits = new Edits("hello") }

now I want to access this from class B

public class B {
Edits edits = new Edits();
String hello = edits.getHello(); }

Problem is that there is and error initializing "new Edits()" because it first has to be set.


Solution

  • The answer here is actually quite simple. All you do it declare a static variable and call it with the class from another class.

    public class Edits {
        public static String edits;
    }
    

    Set it in another class

    public class A {
        Edits.edits = "new value";
    }
    

    Then get it from another class

    public class B {
        doSomething(Edits.edits);
    }