17-Static fields and static methods

The method of static fields and static 
fields in a class are defined, called an instance field. Each instance has its own field of the same name of each field independently of each other examples. With modified static field, called static fields: static Field,. 
Examples of fields in each instance has its own independent "space", but only a static field shared "space", all instances of that class or inherited class instance will share the field, no matter which instance to modify the static field , all instances of static fields have been modified. 
public  class the Main {
     public  static  void main (String [] args) { 
        the Person Ming = new new Student ( " Xiao Ming " , 12 is ); 
        the Person Hong = new new Student ( " Xiao Hong " , 15 ); 
        ming.number = 88 ; / /Modify numbr field ming instance 
        the System. OUT .println (hong.number); // humbr field output hong instance 
        hong.number = 99 ; 
        . The System OUT .println (ming.number); 
    } 
} 

abstract  class the Person { // class static field defines the 
    public String name;
     public  int Age;
     public  static  int Number; 

} 
class Student the extends the Person {
     public Student (String name, int Age) {
         the this .name = name;
        the this .age = Age; 
    }     
} 

Note: not recommended static field to access instance variables static field, recommended by the class name to access static fields. 
Person.number = 99 ; 
the System. OUT .println (Person.number); 

static methods 
static field, there is a static method. With modified static method called static method. Call the instance method must be an instance variable, but you do not need to call the static method instance variables, by class name will be called. Static method similar functions in other programming languages. 
public  class the Main {
     public  static  void main (String [] args) { 
        Person.setNumber ( 99 ); 
        . the System OUT .println (Person.number); 
    } 
} 

class the Person {
     public  static  intNumber; 

    public  static  void setNumber ( int value) { 
        Number = value; 
    } 
} 


Note: Because the static method belonging to class as opposed to instances, therefore, inside a static method, this variable can not access, can not access the instance field, it can only access static fields. 

Static field interface 
as a pure abstract class interface, so it can not be defined instance fields. However, interface can have static fields and static fields must be final type. 
public  interface the Person {
     // compiler will automatically add Statc Final public: 
    int MALE = . 1 ;
     int FEMALE = 2 ; 
} // because the interface is only public static final field type, the compiler will automatically add

 

Guess you like

Origin www.cnblogs.com/nsss/p/11417535.html