[英]How do I call a non-static method from another class in a non-static method? (java)
[英]How can I call a non-static method from another class in Java?
好的,这有点混乱:
我正在使用Netbeans,并且有一个名为ParameterUI的主类。 (这是一个GUI)此类在其GUI上有一些滑块,并且由于这些滑块是私有的,因此我有一个名为getBounds()的方法。 我不想弄乱我的GUI,因此,基本上所有用于计算内容的重要方法都在另一个名为Structure的类中。 因此,ParameterUI调用Structure中的一个方法,该方法本身内部又调用了另外几个方法,其中一个调用getBounds。
问题是getBounds不能是静态的,但如果不是,则不能调用它。
在ParameterUI.class中:
public int[] getBounds () {
int[] bounds = new int[2];
bounds[0] = jSlider2.getMinimum();
bounds[1] = jSlider2.getMaximum();
return bounds;
}
在Structure.class中:
private static void myMethod (Graphics g, double[] planet, long mass) {
int[] bounds = ParameterUI.getBounds(); //<-- doesn't work
}
将myMethod设置为非静态似乎也无济于事。 恐怕虽然我了解静态和非静态的基础知识,但我一直没有使用类等编程。
编辑:本质上,我知道问题是什么,我正在寻找一种更好的方法来解决它。
将ParameterUI实例传递给静态方法
private static void myMethod (ParameterUI param, Graphics g, double[] planet, long mass) {
int[] bounds = param.getBounds(); //<-- doesn't work
}
但是,您可能需要重新考虑要调用其他类的静态方法的设计,以便计算有关第一类的信息。 这表明UI类所需的所有逻辑未包含在其中,并且公共静态方法导致难以测试代码。
静态与非静态
静态的意味着您可以在不实例化该类的对象的情况下访问方法。
非静态意味着您只能从该类的实例访问方法。
您需要确定是否希望ParameterUI类中的方法为静态。
如果将获取范围更改为静态,则它将起作用。
public static int[] getBounds () {
int[] bounds = new int[2];
bounds[0] = jSlider2.getMinimum();
bounds[1] = jSlider2.getMaximum();
return bounds;
}
您可能想先考虑一下。
基础知识:您不能从静态方法访问非静态成员。
您将需要创建实例或将ParameterUI的实例传递到静态方法/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.