Learner_me
Learner_me

Reputation: 29

How can I use a public variable outside a method in two different class files?

I have 2 Class files. Class_login.java and Class_Company.java. I have an xpath stored in different location in a properties file. A method is written in Class_login.java to load this properties file.

static Properties objprop1 = new Properties();
public static FileInputStream fileInputS = null;

static void propManager() throws IOException {
        fileInputS = new FileInputStream("C:\\Test-Automation\\FinanceSys\\myproj\\src\\test\\resources\\xpath.properties");
        objprop1.load(fileInputS);
}

objprop1 is declared outside the method in Class_login.java.
I need to load this file again in Class_Company.java. If I use it like Class_login.PropertyManager(); and use same objprop1 the file does not load and the xpaths are not found.
Hence I created same method with a different name(static void PropertyManager() {) and
public static Properties objprop = new Properties();
I know this is not the correct way. But how can this be done otherwise? In the main method of Class_Company.java I called these methods separately so that I do not get a null xpath error as earlier.

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub

    Class_login LogFeature = new Login();
    Class_Company CC = new CCompany();
    **Class_Company.PropertyManager();**
    LogFeature.OpenBrowser("CH32");
    LogFeature.EnterURL("http://localhost:90/AppFin");
    LogFeature.PageMaximise();
    LogFeature.EnterUserName("uname");
    LogFeature.EnterPassword("abcd!@");
    LogFeature.ClickLoginButton();
    Thread.sleep(2000);
    **Class_Company.propManager();**
    CC.clickNewCompany("Manage");

Please tell me the right way of doing it. I want to use objprop in both the class files and only once in Class_Company.java. and not twice as highlighted above.

Upvotes: 1

Views: 147

Answers (1)

Ishita Shah
Ishita Shah

Reputation: 4035

This is the basic example, which you need:

Global Variable declaration:

Class variableCollection {
public static string data;
}

You can use this variables by extending class Or object references.

class login extends variableCollection{


}

OR

class login{
variableCollection objvar = new variableCollection();

objvar.data = "";

}

You can use this same variable in multiple classes, same way.

Upvotes: 1

Related Questions