开发者

How can I call a non-static method from another class in Java?

Okay, this is a bit messy:

I'm using Netbeans, and I have a main class called ParameterUI. (This is a GUI) This class has a few sliders on its GUI, and since these are private, I have a method called getBounds(). I don't want to clutter up my GUI, and so essentially all the important methods for calculating stuff are in another class called Structure. So ParameterUI calls a method in Structure, which calls another few methods inside itself, and one of these calls getBounds.

The problem is that getBounds can't be static, but I can't call it if it isn't.

In ParameterUI.class :

public int[] getBounds () {
    int[] bounds = new int[2];
    bounds[0] = jSlider2.getMinimum();
    bounds[1] = jSlider2.getMaximum();
    return bounds;
}

In Structure.class :

private static void myMethod (Graphics g, double[] planet, long mass) {
    int[] bounds = ParameterUI.getBounds(); //<-- doesn't work
}

Making myMetho开发者_Go百科d non-static doesn't seem to help either. I'm afraid that while I know the basics about static vs. non-static, I haven't been programming with classes etc. for that long.

Edit: Essentially, I know what the problem is, and I'm looking for a better way to solve it.


Static vs Non-Static

Static means that you can access the method(s) without instantiating an object of that class.

Non-Static means that you can only access the method(s) from an instance of that class.

What you need to do is figure out if you want the methods in the ParameterUI class to be Static or not.

If you change get bounds to be Static, then it will work.

public static int[] getBounds () {
   int[] bounds = new int[2];
   bounds[0] = jSlider2.getMinimum();
   bounds[1] = jSlider2.getMaximum();
   return bounds;
}

You might want to think about it first.


Pass the ParameterUI instance to the static method

private static void myMethod (ParameterUI param, Graphics g, double[] planet, long mass) {
    int[] bounds = param.getBounds(); //<-- doesn't work
}

However you may want to reconsider a design where you are calling into static methods of other classes in order to calculate things about the first class. This suggests that all of the logic necessary for your UI class is not contained in it, and public static methods lead to hard to test code.


Basics : You can't access non static members from static method.

You will need to create instance or pass instance of ParameterUI to/in static method

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜