Definition of instance methods and class methods
When declaring a method, the method type that is not modified by the keyword static is an instance method, and the method type that is modified by the keyword static is a class method, also called a static method.
For example:
classMain{inta;floatmax(floatb,floatc){//Instance method...}staticfloatmax(floatd,floate){//Class method...}}
The difference between instance methods and class methods
1. Object calls instance method:
When the bytecode file of a class is loaded into memory, the instance method of the class will not be assigned an entry address. Only after the class creates an object, the instance method in the class will be assigned an entry address, so that the instance method can be used by any object created by the class. Object call execution.
Notice:
When we create the first object, the instance method in the class is assigned an entry address. When the object is created again, the entry address is no longer assigned. That is to say, the entry address of the method is shared by all objects. When all objects When neither exists, the method's entry address is canceled.
Instance methods can not only operate instance variables, but also class variables. When an object calls an instance method, the instance variables and class variables that appear in the method are variables assigned to the object, but the class variables are shared with all other objects.
2. Call the class method using the class name:
For class methods in a class, when the class is loaded into memory, the corresponding entry address is assigned, so that the class method can not only be called and executed by any object created by the class, but also can be called directly through the class name. The entry address of the class method is not canceled until the program exits.
Notice:
Instance methods cannot be called by class name, only by objects. And because the instance member variables have not allocated memory before the class creates the object, the class method cannot operate the instance variables.
3. Design principles of class methods:
If a method does not need to operate any instance variables in the class to meet the needs of the program, you can consider designing such a method as a static method.
For static methods, you can call it directly with the class name without creating an object. Creating an object will cause instance variables in the class to be allocated memory space.