What is the purpose of the static keyword in this simple example?

Possible duplicate:
When should there be a static method?

Typically, when writing a static method for a class, you can access this method with ClassName.methodName. What is the purpose of using “static” in this simple example and why should / should not be used here? also makes private static damage the goal of using static?

public class SimpleTest { 

   public static void main(String[] args) {
         System.out.println("Printing...");
         // Invoke the test1 method - no ClassName.methodName needed but works fine?
         test1(5);
   }

   public static void test1(int n1) {
         System.out.println("Number: " + n1.toString());
   }
   //versus
   public void test2(int n1) {
         System.out.println("Number: " + n1.toString());
   }
   //versus
   private static void test3(int n1) {
         System.out.println("Number: " + n1.toString());
   }
}

I looked through several guides. For instance. http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

, , , - , , .

+5
8

Static . " ".

test1, Static, , - . Main non-static .

"non-static members cannot be referred from a static context"

.

+1

static , .

; ( ) SimpleTest.

+4

static , . :

SimpleTest st = new SimpleTest();
st.test2(5);

:

SimpleTest.test1(5);

.

private static . , , :

, , ( *) , OO-, "" + , . , - ? -eljenso

+1

static , .

public/protected/private, .

0

, .

, public static , , private static , .

, , . , , , , . - :

class Foo {
    private static int nextId = 0;

    private static int getNext () {
        return nextId ++;
    }

    public final int id;

    public Foo () {
        id = getNext();    // Equivalent: Foo.getNext()
    }
}

, , , :

public static int getInstancesCount () {
    return nextId;
}

ClassName.methodName: , , . , , methodName .

0

test1 main , test1 , main. test2 main, , .

0

, . , ( ), , . (test2 ) , :

new SimpleTest().test2(5);
0

main , , .

static, , . .

0

All Articles