The static keyword (Code practice)

StaticTest class {public 

    String name; // instance attribute, also called non-static property 
    static String address = "Shanxi"; // static property, also known class properties 


    // constructor 
    StaticTest (String name) { 
        this.name = name; 
    } 
    // static method 
    public static void Run the display () { 
        System.out.println ( "the OK"); 
    } 
    // class exists, there is a static method, but only when invoked, will execute 
    public static void print () { 
        System.out.println ( "execute a print static method"); 
        System.out.println (address); 
        //System.out.println(name); can not access the 
        Run the display (); 
        // Show (); // can not access 
    } 

    // example of a method 
    public void Show () {  
        System.out.println ( "show an example of a method performed");
        System.out.println (address + "--show--");
        System.out.println (name + "- show -"); 
        Print (); 
        study (); 
    } 
    public void study () { 
        System.out.println ( "study performed instance method"); 
    } 

} 
class StudentTest { 
    public static void main (String [] args) { 
        System.out.println (StaticTest.address); // static class variable name can be used to directly call 
        //System.out.println(StaticTest.name);// examples variables can not use the class name to access 
        StaticTest STU = new new StaticTest ( "Mama"); 
        System.out.println (stu.name); 
        System.out.println (stu.address); // static variables also can use the object name to call 

        STU = null; 
        //System.out.println(stu.name);// error: null pointer exception
        System.out.println (stu.address); // Note: When members of the object is null, you can access static modified 

        // class name directly call the static method 
        System.out.println ( "------- - "); 
        StaticTest.display (); 
        StaticTest.print (); 
        System.out.println (" -------- "); 

        StaticTest STU2 new new StaticTest = (" Baba "); 
        stu2.show () ; 
        stu2.study (); 
        // object to call a static method 
        System.out.println ( "--------"); 
        stu2.display (); 
        stu2.print (); 
        System.out.println ( " -------- "); 






    } 
}

 

result:

Shanxi
mama
Shanxi Province,
Shanxi Province
--------
the OK
to perform a static method print
Shanxi Province
the OK
--------
performed show examples of methods
Shanxi --show--
baba - show -
implementation of print static methods
Shanxi
OK
to perform a study instance method
performed study instance method
--------
OK
to perform a static method print
Shanxi
OK
--------
 

Published 45 original articles · won praise 8 · views 5852

Guess you like

Origin blog.csdn.net/wenyunick/article/details/104267040