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

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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 myMethod 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.

Answers

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.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/3398876/how-can-i-call-a-non-static-method-from-another-class-in-java

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils