Java:如何从另一个类访问方法 [英] Java: How to access methods from another class

查看:97
本文介绍了Java:如何从另一个类访问方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图尽可能地简化我的困境。我有三个班级:

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
     }
}  

主要:

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

我希望我没有过度简化它。我的问题是如何从Alpha中的方法访问cBeta.DoSomethingBeta()?

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

推荐答案

你需要以某种方式给类Alpha一个cBeta的引用。有三种方法可以做到这一点。

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

1)在构造函数中为Alphas提供Beta。在Alpha类中写道:

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; 
   }

并从main()调用cAlpha = new Alpha(cBeta)

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

2)给Alphas一个改变者,给他们一个beta。在Alpha类中写道:

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;
   }

并调用cAlpha = new Alpha(); cAlpha.setBeta(测试版);从main(),或

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

3)有一个beta作为doSomethingAlpha的参数。在类Alpha中写道:

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

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

您使用哪种策略取决于一些事项。如果您希望每个Alpha都有一个Beta,请使用数字1.如果您只想让一些Alpha拥有Beta,但您希望它们无限期地保留其Betas,请使用数字2.如果您希望Alphas仅处理Betas当你调用doSomethingAlpha时,使用数字3.变量范围最初很复杂,但是当你掌握它时它会变得更容易。如果您还有其他问题,请与我们联系!

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!

这篇关于Java:如何从另一个类访问方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆