JAVA : Accessing static method properly

后端 未结 5 1103
既然无缘
既然无缘 2021-01-05 02:40

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         


        
5条回答
  •  天涯浪人
    2021-01-05 03:14

    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 statics as well. You may want to check that out.

提交回复
热议问题