Reputation: 1987
This is probably a pretty basic question but I can't seem to access the variables from another part of the class I am in. I tried this.p1, this.TwoParamRF.p1, etc etc but I can't get the value of p1 please help. Thanks.
public class SecondMDP {
public SecondMDP(double p1, double p2) {
this.rf = new TwoParamRF(p1,p2);
}
public static class TwoParamRF implements RewardFunction {
double p1;
double p2;
public TwoParamRF(double p1, double p2) {
this.p1 = p1;
this.p2 = p2;
}
}
public String bestActions(double gamma) {
ValueIteration vi=computeValue(gamma);
alert(p1); //Getting error
alert(p2); //here
}
}
Upvotes: 0
Views: 181
Reputation: 180161
I can't seem to access the variables from another part of the class I am in. I tried this.p1, this.TwoParamRF.p1, etc etc but I can't get the value of p1
The value of which p1
? You have a static nested class with a member variable of that name, but it's unclear which instance of that class you want to access.
Your outer class's constructor does assign a value of class TwoParamRF
to an undeclared variable rf
. That object has members p1
and p2
, which the outer class's bestActions()
method could, in principle, access. But it can do so only via a reference of type TwoParamRF
-- if variable rf
is instead declared as a RewardFunction
then you would need to cast it to TwoParamRF
:
((TwoParamRF) rf).p1
But of course that's not type safe. It's a viable approach only if you can rely on rf
always to be a TwoParamRF
, in which case it should be declared that way to begin with, or if you test before casting (e.g. via instanceof
), in which case you need a fallback for when the test fails.
Overall, your code seems to want refactoring. Supposing that rf
is indeed declared as a RewardFunction
, consider what methods you can and should declare for all RewardFunction
s to implement and their clients to use. Consider also what part of bestActions()
' behavior is specific to TwoParamRF
, and how to move that part into TwoParamRF
.
Upvotes: 1
Reputation: 753
The only difference between an external class and a nested static class is possible access to class-private static fields. Otherwise, access rules remain the same. The fields p1
and p2
belong to an object of the nested class, and are not accessible from an instance of the "parent" class; you will need to reference the TwoParamRF
object from the parent class. You should consider putting bestActions()
in the nested class if it only depends on the parameters of the nested class.
Upvotes: 0