Search code examples
javastaticnon-static

Am I using the 'static' keyword correctly?


I am trying to call a class' (Lord.java) method from the main method. When I first tried this Eclipse threw errors about calling non-static methods from a static method. I then changed all the fields/methods to static that Eclipse recommended, and this has fixed the issue. I know there are few situations where static should be used and I am uncertain as to whether I've used the keyword correctly in my code. If not, how can I rewrite this without it?

Main.java

package mainPackage;


public class Main {


static Lord Robert = new Lord(15, 'a');
Lord Renly = new Lord(-5, 'b');
Lord Stannis = new Lord(30, 'b');
Lord Oberyn = new Lord(-60, 'b');
Lord Eddard = new Lord(0, 'a');
Lord Tywin = new Lord(90, 'a');


//Instantiatation ends
int fiefs;

public static void main (String args[]) {
    Robert.giveFief();
    System.out.print(Robert.relationship);
}
}

Lord.java

package mainPackage;

public class Lord {

    protected static int relationship;
    protected char clique;

    public Lord(int a, char b) {
        relationship = a;
        char clique = b;
    }


    public static int giveFief() {
        relationship +=10;
        return relationship;

    }
    }

Solution

  • The static keyword means that you do not require an instance of this type to use a specific field or method. The inverse of that is that if you do have a field that is declared static, then every instance will have the same value.

    In that light, you have a few major problems:

    • relationship will be set to 90 for all instances of Lords. This is obviously not what you want.
    • In Main, you can only interact with Robert inside of main since that's the only variable you've declared that doesn't require an instance of Main to use.

    The first issue is straightforward to fix - remove static from that field. The second one is just as straightforward - remove static from the field and move all of your instantiation statements inside of the main method.