Difference between Static methods and Instance methods

前端 未结 10 1090
青春惊慌失措
青春惊慌失措 2020-11-22 05:30

I was just reading over the text given to me in my textbook and I\'m not really sure I understand what it is saying. It\'s basically telling me that static methods or class

10条回答
  •  情歌与酒
    2020-11-22 05:54

    The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.

    However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.

    You can do this to execute a static method:

    MyClass.staticMethod();  // Simply refers to the class's static code
    

    But to execute a non-static method, you must do this:

    MyClass obj = new MyClass();//Create an instance
    obj.nonstaticMethod();  // Refer to the instance's class's code
    

    On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.

提交回复
热议问题