Today i stumbled over this explanation of the diference of static vs non-static methods, and even though I'm not a java programmer i think it's one of the best i've seen, short and clear while at the same time exposing some of the advantages and implications of choosing one or another. Read the full article here.
/**
 * Java program to show difference between static and non-static method.
 * It explains how calling static method and changing static variable
 * affect all objects, instead of just calling object in case of non-static
 * method
 * @author WINDOWS 8
 *
 */
public class StaticDemo{

    public static void main(String args[]) {
        Player p1 = new Player(10, 10);
        Player p2 = new Player(20, 20);
     
        // calling non-static method move() on p1
        p1.move();
     
        // let's print position of p1 and p2
        // only p1 should have moved, no impact on p2
        System.out.println("P1 : " + p1);
        System.out.println("P2 : " + p2);
     
        // calling static method on p2
        p2.changeGame("Cricket Brian Lara 1997");
     
        // should have affected both p1 and p2
        System.out.println("P1 : " + p1);
        System.out.println("P2 : " + p2);
     
    }
 
 
 
}
/**
 * Simple Java class to represent a Player with position.
 * It has both static and non-static method to operate on
 * player objects.
 * @author WINDOWS 8
 *
 */
class Player{
    private static String game = "Super Mario Bros";
 
    private int X;
    private int Y;
 
    public Player(int x, int y){
        this.X = x;
        this.Y = y;
    }
 
    public void move(){
        X++;
        Y++;
    }
 
    public static void changeGame(String nextGame){
        game = nextGame;
    }
 
    @Override
    public String toString() {
        return String.format("Game: %s, X : %d, Y: %d ", game, X, Y);
    }
}

Output
P1 : Game: Super Mario Bros, X : 11, Y: 11
P2 : Game: Super Mario Bros, X : 20, Y: 20
P1 : Game: Cricket Brian Lara 1997, X : 11, Y: 11
P2 : Game: Cricket Brian Lara 1997, X : 20, Y: 20

Subscreva a Newsletter

maker.akanerd.com

    • Neste site, procura-se documentar alguns projectos do seu mentor, projectos esses, relacionados com áreas como a electrónica, a automação industrial, a informática, desenvolvimento web, sistemas operativos e redes de computadores, entre outros. Conta também com uma área educacional (akanerdemy), onde se apresentam video tutorias nas referidas áreas.