I have the following code class Agent.java :
public class Agent {
Helper helper ;
private class SpecificBehaviour extends Behaviour{
private Apple a;
public SpecificBehaviour(Apple a){
setApple(a);
}
public void setApple(Apple a){
this.a=a;
}
public Apple getApple(){
return a;
}
}
public void someMethod(){
helper = new Helper(this);
}
}
In the Helper.java ( another class within the same package) I would like to access the getApple() method. did some search and found this link
I am wondering if there is a better/ easier way of doing this ?
There are at least two issues here:
Helperdoesn’t know of the existence ofSpecificBehaviour, because it’s a private class. It could potentially know about theBehaviourclass, which you haven’t given any details of. IfgetApple()is declared inBehaviour, and ifBehaviouris visible toHelper, then the visibility part needn’t be a problem.Helperwill need a reference to an instance ofSpecificBehaviour, which means you’ll need to instantiateSpecificBehaviour. For that, you’ll also need an instance ofAgent, becauseSpecificBehaviouris an inner class. It’s not clear whether you have such an instance.Basically I think the presence of a private inner class is adding confusion here. If you’re reasonably new to Java, I’d strongly recommend sticking to top-level classes for the moment. They have a few subtleties around them, and it’s best to try to learn one thing at a time.
If this doesn’t help, please give more context – your question is quite vague at the moment. Where do you want to use
getApplewithinHelper? Should part of the state ofHelperbe a reference to an instance ofSpecificBehaviour, or should it be a method parameter? Have you created an instance ofAgent? What doesBehaviourlook like? You may find that in the course of answering these questions one at a time, you’re better able to figure out the problem for yourself.