This is an instance method !!! For an method
or attribute
of class you need explicit use static
modifier. You are creating an instance of Animal and calling the method dump()
on this instance. See my example:
public class Animal {
static int x = 0; // is an attribute of class
int y = 0; // is an instance attribute
static void myStaticMethod() { // is an method of class
x++; // increment the class attribute
// y++; wrong, compilation error !!! y is an instance attribute
}
void myMethod() { // is an instance method
y++; // increment the instance attribute
x++; // increment the class attribute
}
}
Another thing about this is, static attributes/methods are assigned to memory on compilation time, while non-static attributes/methods are assigned to memory on execution time. The life-cycle of static attribute/method starts on program execution and ends at end of execution, instance attribute/method lasts (in Java) while reference count for this instance if above then 0, on reference count is 0 the garbage collector frees the allocated memory for this instance. Look:
Animal cat = new Animal();
Animal.myStaticMethod();
cat.myMethod();
Animal dog = new Animal();
Animal.myStaticMethod();
dog.myMethod();
dog.myMethod();
System.out.println("Animal::x = " + Animal.x);
System.out.println("cat::y = " + cat.y);
System.out.println("dog::y = " + dog.y);
Output is (without y++ on myStaticMethod):
Animal::x = 5
cat::y = 1
dog::y = 2