如何从父类到子类获取字符串?请检查我的代码,让我知道如何做到这一点?我想从父类到子类获取字符串。
public class ExtendExamle {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file=new File("D:\\softs\\IEDriverServer_Win32_2.42.0\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();
driver.get("https://www.gmail.com");
}
public static class Test extends ExtendExample {
public static void main(String[] args) {
}
}
}
答案 0 :(得分:2)
当一个类扩展另一个类时,子类会自动继承任何可见变量(未标记为private
或没有访问修饰符的变量)。
class ParentClass {
protected String url = "www.stackoverflow.com";
}
class ChildClass extends ParentClass { //automatically inherits url
public void run() {
//im guessing this class is where you want to use url?
System.out.println(url);
}
}
//A class to start to program
class Main {
public static void main(String[] args) {
ChildClass child = new ChildClass();
child.run();
}
}
ChildClass将自动从ParentClass继承String,允许您在ChildClass中使用url,而无需额外的工作。
答案 1 :(得分:0)
在父类中添加一个公共静态方法以返回String。
public class A {
private static String string;
public static String getString() { return string; }
...
}
public class B extends A {
private String string = A.getString();
...
}