[英]How to call a variable from one java class in a different class
我遇到一個問題,我需要在另一個Java類中調用在一個Java類中創建的變量。
Course.java
public class Course {
public String courseName;
SecondCourse.java
public class SecondCourse {
Course courseName;
@Before
public void setUp() throws Exception {
courseName = new Course();
盡管我已經像這樣設置了,但在SecondCourse.java類中,該變量調用不起作用。 我錯過了什么嗎? 你能幫助我嗎?
我正在嘗試打電話
driver.findElement(By.xpath("//div/input")).sendKeys(courseName);
在SecondCourse.java類中。 但是給我錯誤org.openqa.selenium.WebElement中的錯誤sendKeys(java.lang.CharSequence ...)
首先,您在Course.java類中定義
public class Course
{
public static String courseName; //Define variable as static here
}
使用類名在任何類中訪問該變量
Course.courseName = "abc"; // /Access this variable
SecondCourse
Course courseName
定義了Course
類型的成員字段-它不對應於Course
String courseName
。 你可以,如果你願意,訪問courseName
的字符串Course
存儲在對象courseName
Course
的SecondCourse
使用courseName.courseName
。
只需在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);
}
不能100%確定您的總體目標是什么,但這可能會有所幫助。
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
*/
}
}
Course類初始化並授予對其的courseName變量的訪問權限,第二課程使用Course類提供的功能對課程進行其他工作。
此外,這篇關於封裝的文章可能很有用。
使用Course.courseName
,您將可以訪問其他類變量。 希望能幫助到你。 謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.