简体   繁体   中英

JAVA get the value from one class to another

How can i get the value of string from class a to class b ?

public class A{
public String string = "A";
}

public class B{
public static void main(String []args){
   System.out.printl(string);
           }
}

You have to instantiate the class A and access the instance variable. Like this:

public class A{
    public String string = "A";
}

public class B{
    public static void main(String []args){
         A a = new A();
         System.out.println(a.string);
    }
}

string is an instance variable of class A.

Firstly, you cannot have two public classes in the same file.

So I suggest that you move class A to A.java and leave the class B in B.java

A.java

public class A{
    public String string = "A";
}

B.java

public class B{
    public static void main(String []args){
         A a = new A();
         System.out.println(a.string);
    }
}

Upon invoking class B , a new object of class A would be create and the variable of A can be access through it.

public access to member fields cause so many problems, fix them before you have them with a technique of hiding them behind a method.

public class A {

    public String getString() {
      return "A";
    }
}

public class B{
    public static void main(String []args){
         A a = new A();
         System.out.println(a.getString());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM