Static变量或方法

听说华为H3C面试问了这样一个问题,在main方法前加了static关键字有什么作用,虽说static经常见经常用,但我也不甚了了。赶紧查了资料:

static variables: all the instances of a class to share data, Static variables store values for the variables in a common memory location. Because of this common location, all objects of the same class are affected if one object changes the value of a static variable. 

Static methods:  can be called without creating an instance of the class.

Static variables and methods can be used from instance or static methods in the class. However, instance variables and methods can only be used from instance methods, not from static methods, since static variables and methods belong to the class as a whole and not to particular objects.

How do you decide whether a variable or method should be an instance one or a static one? A variable or method that is dependent on a specific instance of the class should be an instance variable or method. A variable or method that is not dependent on a specific instance of the class should be a static variable or method. For example, every circle has its own radius. Radius is dependent on a specific circle. Therefore, radius is an instance variable of the Circle class. Since the getArea method is dependent on a specific circle, it is an instance method. None of the methods in the Math class, such as randompowsin, and cos, is dependent on a specific instance. Therefore, these methods are static methods. The main method is static, and can be invoked directly from a class.

It is a common design error to declare an instance method that should have been declared static.

你可能感兴趣的:(object,面试,Class,h3c,methods,variables)