繁体   English   中英

如何从另一个类中的一个Java类调用变量

[英]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 CourseSecondCourse使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM