简体   繁体   中英

Why is possible to call static methods of a non-static class?

Taking into consideration the following class structure:

[PUBLIC NON-STATIC CLASS]

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {

    public static void Play() //STATIC METHOD
    {
        print("Play some audio!");
    }

}

ANOTHER CLASS CALLING:

using UnityEngine;
using System.Collections;

public class TestClass : MonoBehaviour {

    // Use this for initialization
    void Start () {
        GameManager.Play();
    }

    // Update is called once per frame
    void Update () {

    }
}

Because it is possible to call this method without instantiating the class GameManager?

From here

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated

The fact that it's not a static class doesn't affect the way static methods can be used.

Static methods are often used in a non-static class for utility methods. They can also be used for masking modifiers and constructors on immutable types by returning a new object from the requested manipulation. See java String.

The difficulty comes from the fact that 'static' has a slightly different meaning for methods and for classes.

  1. Static classes cannot be instantiated
  2. Static methods are associated with the class rather than objects, so you don't need to create an object to call a static method. However, it does not matter if the class itself is static or not.

See the relevant documentation here .

当方法声明为static时 ,可以在创建其类的任何对象之前对其进行访问,并且无需引用任何对象,并且非静态类也可以包含静态方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM