I am new to JAVA, and I like to try and understand everything.
When accessing a static method \"hero.returnHp()\" in JAVA, I have the following:
he
A static
method is one which belongs to a class but not to an object. In your example above, you have created an object Mike
of class hero
. The method returnHp()
is static
, and belongs to the hero
class, not the hero
objects (such as Mike
).
You will likely get an IDE or compiler warning when you reference a static
method from an object, because it should never be tied to that object, only to its class.
Based on the method name, I would guess it shouldn't be static.
class hero {
private float hp;
public float returnHp() { // Should NOT be "public static float ..."
return hp;
}
}
The JavaDocs on class members has a brief discussion on static
s as well. You may want to check that out.