简体   繁体   中英

Passing variable from another file and then use variable within to another method within same class

I am trying to call a variable from another class in another to the second java file

public class selectFile {
    public void hdrFile(){
        String hdrName = "directory";
        readImage sendVari = new readImage();

        sendVari.setprintHDR(hdrName);
    }
}

public class readImage {
    private String hdr_dir;

    public static void main(String[] args){
        selectFile call_vari = new selectFile();
        call_vari.hdrFile();
    }

    public void setprintHDR(String hdr_dir){
        this.hdr_dir = hdr_dir;
    }

    public String getprintHDR(){
        return hdr_dir;
    }

    public void anotherMethod(){
        System.out.println(getprintHDR());
    }
}

I am doing this because I want to use "anotherMethod" Method in second in the third file, but when I am testing in the second java file by printing it to the terminal "anotherMethod" cannot print any hdr_dir even I return hdr_dir. But if I check "setprintHDR" by printing it to the command everything seem fine, it returns "directory"

public class Main {
    public static void main(String[] args){
        readImage call_vari = new readImage();
        call_vari.anotherMethod();
    }
}

Since you want to use the updated value in another object( basically trying to share the value between multiple objects), you should keep your variable hdr_dir as static . Static vs Instance Variables: Difference?

You were currently using the variable as instance one due to which if one object updates the value, it will remain specific to that object only. For your main class,

public class Main {
    
//    private String hdr_dir;

    public static void main(String[] args){
        int res = 0; 
         selectFile call_var = new selectFile();
         call_var.hdrFile();
        readImage call_vari = new readImage();
//        call_var.anotherMethod();
//        call_vari.setprintHDR("printHDR");
        call_vari.anotherMethod();
    }
}

and the output is

value of hdr_dir is passed is  -------directory // doing some console logging 
value of hdr_dir assigned is  -------directory
directory

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