如何在同一包中的当前 java 文件中使用其他 java 文件的变量?

How to use variable of other java file in current java file within same package?

MouseActions.java 文件的驱动程序对象为 FirefoxDriver class。 我有另一个 keyactions.java 文件,我已将此 class 扩展为 MouseActions.java.

现在我想在 keyactions.java 文件中使用 MouseActions.java 文件的驱动程序对象,而无需实例化新对象。

但我收到错误 "multiple markers at the line"

MouseActions.java 文件:

package myproject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class mouseOverEvent
{
    public static void main(String[] args) {
        WebDriver driver=new FirefoxDriver();
        driver.get("http://www.google.co.in");
        Actions Builder=new Actions(driver);
        WebElement home=driver.findElement(By.xpath(".//*[@id='tsf']/div[2]/div[3]/center/input[2]"));
        Action mouseOverHome= Builder.moveToElement(home).click().build();
        mouseOverHome.perform();
    }
}

keyactions.java 文件:

package myproject;

public class KeyStrokesEvent extends mouseOverEvent{    
    driver.get("http://www.facebook.com");  
}
WebDriver driver=new FirefoxDriver();

驱动变量是在方法中定义的,其作用域仅限于方法。它不能在它之外访问。

您需要在子class中声明为class级别才能访问。要在不创建对象的情况下访问它,将其声明为 static 变量并使用 class 名称访问它。

我想知道为什么要将 Main class 扩展到其他 class?

您是否尝试过将驱动程序变量设置为全局变量?

package myproject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;


public class mouseOverEvent {
    WebDriver driver=new FirefoxDriver();
    public static void main(String[] args){
        driver.get("http://www.google.co.in");
        Actions Builder=new Actions(driver);
        WebElement home=driver.findElement(By.xpath(".//*[@id='tsf']/div[2]/div[3]/center/input[2]"));
        Action mouseOverHome= Builder.moveToElement(home).click().build();
        mouseOverHome.perform();
    }
}

该变量是方法 main() 的本地变量,这就是为什么您不能在该方法之外访问它的原因。然而,使其成为全球性的,使其易于访问。