co757 co757 - 3 months ago 8
Java Question

Java: How to access methods from another class

I tried to simplify my predicament as much as possible. I have three classes:

Alpha:

public class Alpha {
public void DoSomethingAlpha() {
cbeta.DoSomethingBeta() //?
}
}


Beta:

public class Beta {
public void DoSomethingBeta() {
// Something
}
}


Main:

public class MainApp {
public static void main(String[] args) {
Alpha cAlpha = new Alpha();
Beta cBeta = new Beta();
}
}


I hope I did not over simplify it. My question is how do I access cBeta.DoSomethingBeta() from a method in Alpha?

Answer

You need to somehow give class Alpha a reference to cBeta. There are three ways of doing this.

1) Give Alphas a Beta in the constructor. In class Alpha write:

public class Alpha {
   private Beta beta;
   public Alpha(Beta beta) {
     this.beta = beta; 
   }

and call cAlpha = new Alpha(cBeta) from main()

2) give Alphas a mutator that gives them a beta. In class Alpha write:

public class Alpha {
   private Beta beta;
   public void setBeta (Beta newBeta) {
     this.beta = beta;
   }

and call cAlpha = new Alpha(); cAlpha.setBeta(beta); from main(), or

3) have a beta as an argument to doSomethingAlpha. in class Alpha write:

public void DoSomethingAlpha(Beta cBeta) {
      cbeta.DoSomethingBeta()
}

Which strategy you use depends on a few things. If you want every single Alpha to have a Beta, use number 1. If you want only some Alphas to have a Beta, but you want them to hold onto their Betas indefinitely, use number 2. If you want Alphas to deal with Betas only while you're calling doSomethingAlpha, use number 3. Variable scope is complicated at first, but it gets easier when you get the hang of it. Let me know if you have any more questions!