Java Learning Note Eight how to access and invoke static variables and static methods---classes

Source: Internet
Author: User

Static variables are also called class variables, and static methods are called class methods, which are collectively referred to as static members or class members. Static members are decorated by static and belong to the entire class, and all of the objects share these static members. You do not need to create any objects, static members are initialized when the class is loaded, and their memory location is unchanged throughout the run until the class unloads. Because of these characteristics of static members, accessing static variables and defining or invoking static methods differs from non-static members. The following are explained separately.

1. Static variables

    • Static variables can be accessed directly by non-static methods and static methods of the class
    • Other classes to access the static variables of a class, either through the instance name access, or directly with the class name to access, it is recommended to access the class name, so that the more intuitive to describe the variable is a static variable

2. Static methods

    • You cannot directly access a non-static variable, you cannot call a non-static method directly, you need to instantiate an object, and then use that object to access the non-static variable or non-static method to invoke. In other words, a static method cannot directly use a non-static member. Personal understanding is that non-static members are dependent on the object, when there is no instance of an object, non-static members are not allocated memory space, static methods to use non-static members do not know where to go to find, of course, can not directly use non-static members.
    • Other classes to invoke a static method of a class, either by the instance name can be called, or directly with the class name to invoke, it is recommended to call the class name, so that the call is more intuitive way to describe the static method

3. Verify the above conclusions with a simple code

A person class is defined, and the code for the class is shown in the last face.

(1). Static methods of the class can access static variables directly

    • Static method Staticmethod accesses the static variable citizenship
    • Local variables are defined and used testy

The Staticmethod () method is as follows:

public static void Staticmethod () {int testy = 20; System.out.println ("She has applied for" + Citizenship + "citizenship"); Static variable accessSystem.out.println ("She ' s Now" + testy + "Years");  Local variable access
}

The main () method is as follows:

public static void Main (string[] args) {person xiaoxi = new Person ("Xiaoxi", "female", "Piano"); Xiaoxi.informationprint (); Staticmethod ();}

The output results are as follows:

My name is XIAOXII am years oldi am a girlmy hobby is pianoi am a chineseshe have applied for Chinese Citizenshipshe ' s n OW years old

Results Analysis:

    • Static methods can access static variables directly
    • Static methods can customize local variables

(2), static methods can not directly access non-static variables

[1].staticmethod direct access to static variable citizenship, error occurred

    • Static method Staticmethod accesses the static variable citizenship
    • Local variables are defined and used testy
    • Accessed non-static variable hobby

The Staticmethod () method is as follows:

public static void Staticmethod () {int testy = 20; System.out.println ("She has applied for" + Citizenship + "citizenship"); Static variable accessSystem.out.println ("She ' s Now" + testy + "Years");  Local variable accessSystem.out.println ("She doesn ' t like" + hobby); nonstatic variable Access}

The Main method is ibid.

The output results are as follows:

My name is XIAOXII years oldi am a girlmy hobby are pianoi am a chineseexception in thread "main" java.lang.Error:Un Resolved compilation Problem:cannot make a static reference to the Non-static field Hobbyat human. Person.staticmethod (person.java:99) at human. Person.main (person.java:107)

Results Analysis:

    • Static methods cannot directly access non-static variables, otherwise "cannot make a static reference to the Non-static field hobby" error occurs.

[2].staticmethod () creates an object TESTP, TESTP accesses the non-static variable hobby, successfully executes

    • static method Staticmethod uses a static variable citizenship
    • Local variables are defined and used testy
    • Create a person instance TESTP, and use the TESTP variable hobby

The Staticmethod () method is as follows:

public static void Staticmethod () {int testy = 20; Person TESTP = new person (); System.out.println ("She has applied for" + Citizenship + "citizenship"); Static variable accessSystem.out.println ("She ' s Now" + testy + "Years");  Local variable accessSystem.out.println ("She doesn ' t like" + testp.hobby); Nonstatic variable access via object instance TESTP}

The Main method is ibid.

The output results are as follows:

My name is XIAOXII am years oldi am a girlmy hobby is pianoi am a chineseshe have applied for Chinese Citizenshipshe ' s n ow years Oldshe doesn ' t like null

Results Analysis:

    • Static methods to access non-static variables, you can instantiate an object and then access it through the object.

(3), static methods can not directly call non-static methods

[1].staticmethod () direct access non-static method Informationprint (), error occurred

    • static method Staticmethod uses a static variable citizenship
    • Local variables are defined and used testy
    • Create a person instance TESTP, and use the TESTP hoppy variable
    • Calling non-static methods directly Informationprint ()

The Staticmethod () method is as follows:

public static void Staticmethod () {int testy = 20; Person TESTP = new person (); System.out.println ("She has applied for" + Citizenship + "citizenship"); Static variable accessSystem.out.println ("She ' s Now" + testy + "Years");  Local variable access//system.out.println ("She doesn ' t like" + testp.hobby); nonstatic variable accessSystem.out.println ("She doesn t like" + testp.hobby); Nonstatic variable access via object instance TestPSystem.out.println ("Her personal information was as follows:"); inform Ationprint ();}

The main () method is the same as above.

The output results are as follows:

My name is XIAOXII years oldi am a girlmy hobby are pianoi am a chineseexception in thread "main" java.lang.Error:Un Resolved compilation Problem:cannot make a static reference to the Non-static method Informationprint () from the type Per Sonat Human. Person.staticmethod (person.java:103) at human. Person.main (person.java:111)

Results Analysis:

    • A static method cannot invoke a non-static method directly, otherwise it will appear similar to the direct access non-static variable, cannot make a static reference to the Non-static method Informationprint () from the T ype person.

[2]. Call the Informationprint () method with an existing object TESTP to execute successfully

    • static method Staticmethod uses a static variable citizenship
    • Local variables are defined and used testy
    • Create a person instance TESTP, and use the TESTP hoppy variable
    • Calling non-static methods via TESTP Informationprint ()

The Staticmethod () method is as follows:

public static void Staticmethod () {int testy = 20; Person TESTP = new person (); System.out.println ("She has applied for" + Citizenship + "citizenship"); Static variable accessSystem.out.println ("She ' s Now" + testy + "Years");  Local variable accessSystem.out.println ("She doesn ' t like" + testp.hobby); Nonstatic variable access via object instance TestPSystem.out.println ("Her personal information was as follows:");//info Rmationprint (); Testp.informationprint ();}

The main () method is the same as above.

The output results are as follows:

My name is XIAOXII am years oldi am a girlmy hobby is pianoi am a chineseshe have applied for Chinese Citizenshipshe ' s n ow years Oldshe doesn ' t like Nullher personal information are as Follows:my name is Nulli AM 0 years oldsomething is WRO ng! My Hobby is nulli am a Chinese

Results Analysis:

    • Static methods to invoke a non-static method, you can instantiate an object and then invoke it through the object.

Attached Person class:

Package Human;public class Person {String name;int age; String Gender;private string hobby;protected string residence;static String citizenship = "Chinese";p ublic person () {}pub LIC person (string n, String g) {this.name = N;this.gender = g;} public person (string n, int A, string g, String h) {this.name = N;this.age = A;this.gender = G;this.hobby = h;//test: initial static variable Whether the timing of the initiation is System.out.println before the method is constructed ("constructor:"); SYSTEM.OUT.PRINTLN ("Change value of the the static variable citizenship" + "\" "+ Citizenship +" \ ""); citizenship = "US"; System.out.println ("to" + "\" "+ Citizenship +" \ "");} public person (string n, int A, string g, String h, String r) {this.name = N;this.age = A;this.gender = G;this.hobby = h;th Is.residence = r;} public void SetName (String n) {this.name = n;} public void Setage (int a) {this.age = A;} public void Setgender (String g) {this.gender = g;} public void Sethobby (String h) {this.hobby = h;} public void Setresidence (String r) {this.residence = R;} Public String GetName () {return thiS.name;} public int getage () {return this.age;} Public String Getgender () {return this.gender;} Public String Gethobby () {return this.hobby;} Public String getresidence () {return this.residence;} public void Informationprint () {System.out.println ("My name is" + getName ()); System.out.println ("I Am" + getage () + "years old"), if (getgender () = = "female") System.out.println ("I Am a Girl"); ElseIf ( Getgender () = = "Male") System.out.println ("I am A Boy"), ElseSystem.out.println ("Something is wrong!"); System.out.println ("My hobby is" + hobby), if (Citizenship = = "Chinese") System.out.println ("I am a Chinese");//test: Whether the static variable initializes the ElseIf (citizenship = = "US") System.out.println ("I am an American") before constructing the method; ElseSystem.out.println ("Oh, Something is Wrong ");} public static void Staticmethod () {int testy = 20; Person TESTP = new person (); System.out.println ("She has applied for" + Citizenship + "citizenship");  Static variable accessSystem.out.println ("She ' s Now" + testy + "years"); Local variable AccesssystEm.out.println ("She doesn ' t like" + testp.hobby); Nonstatic variable access via object instance TestPSystem.out.println ("Her personal information was as follows:");//info Rmationprint (); Testp.informationprint ();} public static void Main (string[] args) {person xiaoxi = new Person ("Xiaoxi", "female", "Piano"); Xiaoxi.informationprint (); Staticmethod ();}}

  

Java Learning Note Eight how to access and invoke static variables and static methods---classes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.