I ran into an issue, where I need to call a variable created in one java class in another java class.
Course.java
public class Course {
public String courseName;
SecondCourse.java
public class SecondCourse {
Course courseName;
@Before
public void setUp() throws Exception {
courseName = new Course();
Eventhough, I have set up it like this, the varible call doesn't work in SecondCourse.java Class. Have I missed something? Can you help me?
I'm trying to call
driver.findElement(By.xpath("//div/input")).sendKeys(courseName);
in the SecondCourse.java class. But gives me the error sendKeys(java.lang.CharSequence...) in org.openqa.selenium.WebElement cannot be applied
First of all you define in your Course.java class
public class Course
{
public static String courseName; //Define variable as static here
}
Access that variable in any class using class name
Course.courseName = "abc"; // /Access this variable
Course courseName
of SecondCourse
defines a member field of type Course
- it does not correspond to String courseName
of Course
. You can, if you want, access the courseName
string of the Course
object stored in courseName
Course
of SecondCourse
using courseName.courseName
.
Simply In SecondCourse.java
public class SecondCourse {
Course obj = new Course(); // creates new obj for Course class
@Before
public void setUp() throws Exception {
//courseName = new Course(); //You won't need this.
system.out.println("Here is how your obj can be called "+ obj.courseName);
}
Not 100% sure what your overall goal is, but this might prove helpful.
public class Course {
private String courseName;
public Course(String courseName) {
this.courseName=courseName;
}
public String getCourseName() {
return this.courseName;
}
}
public class SecondCourse {
private Course course;
public SecondCourse(String courseName) {
course=new Course(courseName);
}
public void setup() {
String courseName=course.getCourseName();
/*
* Do something with courseName
*/
}
}
The Course class initialize and grants access to it's courseName variable and the Second Course does additional work on the course using the functionality given by the Course class.
In addition this post on encapsulation may prove useful.
Use Course.courseName
, u will be able to access the other class variable. Hope it helps. Thanks.
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.