Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- use a variable from another file

Tags:

java

How can I use a variable from another file? I am writing automation tests (Selenium and TestNG). I want to store some data variables and xpaths in a separate file (secondFile.java)

Master File:

import secondFile.help;

public class TicketAdminTestSuite extends something {

       void printStuff(){
            System.out.println(bar);
} 

}

==============================================

Helper file (name: help.java):

public class help  {
    public static final String bar = "blah";
}
like image 413
user2195411 Avatar asked Dec 04 '25 12:12

user2195411


2 Answers

There are two severe errors in your code:
- the helper file name must be the same as the class name
- the import in the master file must import the helper file with the full package name (I assume the files are in the same package)

// master file TicketAdminTestSuite.java
import Help;
public class TicketAdminTestSuite extends something {

   void printStuff(){
        System.out.println(Help.bar);
   } 
}

// help file Help.java
public class Help  {
    public static final String bar = "blah";
}
like image 189
robin Avatar answered Dec 07 '25 04:12

robin


Just write help.bar:

   void printStuff(){
        System.out.println(help.bar);

But this example is a bit confusing because the public class must be called the same as the .java file. And if you made a second class in the secoundfile you wouldn't be able to access it from your first file. This would be a better example: import secondFile;

public class TicketAdminTestSuite extends something {

   void printStuff(){
        System.out.println(secondFile.BAR);
} 

}

And the second file is made like this

public class secondFile  {
     public static final String BAR = "blah";
}
like image 43
Tilion Avatar answered Dec 07 '25 05:12

Tilion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!