1 /*2 static (statically)3 4 Requirement: Describe the class of the student of wisdom. It's all Chinese ....5 6 7 existing problems: All students are Chinese, there are n students will have n copies of China's data in memory, so that the child8 will waste memory. 9 Ten Current Program: The "China" this data to the data sharing area, sharing this data for all student objects to use. One A Question 2: How can I move this data to a data share? - - solution: Just use static to decorate the data. the - - static member variables maintain only one copy in the data share, and the data for non-static member variables is maintained in one copy of each object. - + */ - + classstudent{ A at String name; - - //with the static modifier country, then country is a shared data. - - StaticString country = "China";//Nationality - in //constructor Function - PublicStudent (String name) { to This. Name =name; + } - } the * classDemo9 { $ Panax Notoginseng Public Static voidMain (string[] args) - { theStudent S1 =NewStudent ("Zhang San"); +Student s2 =NewStudent ("Chen Qi"); A theS1.country = "Little Japan"; +System.out.println ("Name:" +s1.name+ "Nationality:" + s1.country);//China -System.out.println ("Name:" +s2.name+ "Nationality:" + s2.country);//Little Japan $ } $}
1 /*2 static \ Modifier3 4 1. Static modifier member Variable: You can use the static modifier if there is data that needs to be shared with all objects. 5 6 how static member variables are accessed:7 8 Mode 1: You can use objects for access. 9 format: Object. Variable name. Ten One method Two: You can use the class name for access. A format: class name. variable name; - - Note: the 1. Non-static member variables can only be accessed using an object and cannot be accessed using the class name. - 2. Do not use static modifier member variables for easy access to data, only when data for member variables is really needed to be shared - before using the static modifier. - + static Modify the application scenario for member variables: If a data needs to be shared by all objects, this is a good time to use static adornments. - + A 2. Static modifier member function: at - */ - - classstudent{ - - StaticString name;//non-static member variable in - StaticString country = "China";//Static member variables to + PublicStudent (String name) { - This. Name =name; the } * } $ Panax Notoginseng - classDemo10 { the + A Public Static voidMain (string[] args) the { +Student S1 =NewStudent ("Dog Doll")); -Student s2 =NewStudent ("The Dog left"); $ $ //System.out.println ("Nationality:" + student.country); -System.out.println ("Name:" +s1.name); -System.out.println ("Name:" +s2.name); the } -}
Java Road Static