Hello, I'm new to OOP and Java and I have a problem I have been unable to solve.
I have searched many books and online and can't seem to find a solution that works.
Hoping someone here can enlighten me as to what I am doing wrong.
I have some user preferences in a desktop application that I want to be able to
access from several classes in my package.
Specifically, I need to set some variables in a class then access the values from other classes.
Here is a representation of what I am trying to do:
Code:
public class A { // the setup class, initialize and set the variable value
private String aString = "";
public A {
}
public void setAString(String aString) {
this.aString = aString;
}
public String getAString() {
return aString;
}
public void initString() { // actually reads the value from a file in my code
aString = "abc";
}
}
public class B { // try to initialize the variable and get the value from class A
public initVar() {
A a = new A();
a.initString(); // makes class A set the variable value (read the file in my code)
}
public doSomething() {
//get the variable value from class A
String newString = a.getString(); // returns null from class A
}
}
Why does a.getString in doSomething return null instead of "abc"?
What do I need to change?
Thanks if you can help!