Object-oriented foundation--static use of keywords and code blocks

Source: Internet
Author: User

Specific contentyou can use static to declare properties and methods in Java, because the previous multipart properties and methods are non-static, so that each object occupies its own content, and if you want a property to be owned by all objects now, you can declare it as a static type. This property or method is also known as a class non after a property and method declared as a static type, and can be called directly by the class name. declaring properties with staticstatic can declare global properties, what is the role of global properties? As shown below
Class person{//defines the person class string name;//define the Name property, and temporarily do not encapsulate int age;//define the Age property, and temporarily do not encapsulate string country = "a city";//define city attributes with default values Publi C Person (String Name,int age) {this.name = name; this.age = age;} public void info () {//Get information System.out.println ("Name:" + THIS.name + ", Age:" + This.age + ", City:" + Country);}};  public class Staticdemo01{public static void Main (String args[]) {person P1 = new Person ("Zhang San", 30);//instantiation of object person P2 = new Person ("John Doe", 31); Instantiate object Person p3 = new Person ("Harry", 32); Instantiate Object P1.info ();p 2.info ();p 3.info ();};


Although the above code has implemented some basic functions, but if the city name is not called a city, and changed to B city, if now has produced 5,000 objects, name means, at this time need to modify the 5,000 object's Country property, Therefore, it is best to use the static keyword to declare it at this time. Use this to modify program properties
Class person{//defines the person class String name;//define the Name property, and temporarily do not encapsulate int age;//define the Age property, temporarily do not encapsulate the static String country = "a city";//define city attributes, have a default Recognition value, staticpublic person (String Name,int age) {this.name = name; this.age = age;} public void info () {//Get information System.out.println ("Name:" + THIS.name + ", Age:" + This.age + ", City:" + Country);}};  public class Staticdemo02{public static void Main (String args[]) {person P1 = new Person ("Zhang San", 30);//instantiation of object person P2 = new Person ("John Doe", 31); Instantiate object Person p3 = new Person ("Harry", 32); Instantiate object System.out.println ("-------------before---------------modification");p 1.info ();p 2.info ();p 3.info ();p 1.country = "b City";// Modify the static property System.out.println ("---------------modified-------------");p 1.info ();p 2.info ();p 3.info ();}};


modifying the Country property of an object will change the country property of the other object. Because country is a variable shared by all objects in the class.
Each object has its own stack space, and the heap memory space holds its own properties for each object, but all static properties are stored in the global data area, and all objects point to one content in the global data area, so when an object is modified, the contents of all objects change. The following memory areas are available in Java:Stack Memory: The name of the object can be saved (save, the address of the heap memory accessed)Heap Memory: Saves the specific properties of each object. Global Data area: Saving properties of static typeGlobal Code area: Saves the definition of all methods. It is generally preferable to call the static property using the class name, called in the form "Class name. Property". Person.country = "b City";You can use static to declare properties directly, or you can use the static declaration method. using the static declaration methodIf a method is declared with the static keyword, this method can be called directly using the class name, which encapsulates the properties in all previous code.
class person{//defines the person class private string name;//defines the Name property, temporarily does not encapsulate the private int age;//defines the Age property, temporarily does not encapsulate the private static String country = "A city";//define a city property with a default value, Staticpublic static void Setcountry (String c) {//This method can be called directly by the class name country = C;} public static String Getcountry () {return country;} Public person (String Name,int age) {this.name = name; this.age = age;} public void info () {//Get information System.out.println ("Name:" + THIS.name + ", Age:" + This.age + ", City:" + Country);}};  public class Staticdemo04{public static void Main (String args[]) {person P1 = new Person ("Zhang San", 30);//instantiation of object person P2 = new Person ("John Doe", 31); Instantiate object Person p3 = new Person ("Harry", 32); Instantiate object System.out.println ("-------------before---------------modification");p 1.info ();p 2.info ();p 3.info (); Person.setcountry ("b City");//Call the static method to modify the contents of the static property System.out.println ("---------------modified-------------");p 1.info (); P2.info ();p 3.info ();}}; 


Note: You cannot invoke a property or method that is not static by using the static method. For example, the following code is wrong:
Class person{//defines the person class private static string country = "a city";//define static property private String name = "Hello";p ublic static void Sfun (String c) {System.out.println ("name =" + name);//error, cannot invoke non-static property fun ();//error, cannot call non-static method}public void Fun () {Syst EM.OUT.PRINTLN ("World");};

Because static properties or methods can be called directly when an object is not instantiated, the non-static property must be called after the object is instantiated.static Application One: Count how many objects a class actually produces.
Class demo{//defines the person class private static int count = 0;//All objects share this property public Demo () {count++;//As long as there is object generation it should be self-increment System.out.println ("generated" + Count + "Objects!) ") ;} }; public class Staticdemo06{public static void Main (String args[]) {new demo ();//Add object to the demo ();//Add New object to Demo ();//Add New Object}};


Static Application Example two: You can use static to automatically name an object
Class demo{//defines the person class private String name;//save name private static int count = 0;//All objects share this property public Demo () {count++;//Object Generated on self-increment this.name = "demo-" + count;//automatic name Operation} public DEMO (string name) {this.name = name;//can be constructed by constructing an assignment}public String getName () {//Get name return this.name;}}; public class Staticdemo07{public static void Main (String args[]) {System.out.println (New Demo (). GetName ()); System.out.println (New Demo ("Lxh"). GetName ()); System.out.println (New Demo (). GetName ()); System.out.println (New Demo ("Mldn"). GetName ()); System.out.println (New Demo (). GetName ());};


Summary of Use of static:properties or methods that use the static declaration can be called directly by the class name. when using the static method, it is important to note that only the properties or methods of the static declaration can be accessed, and not the properties and methods of the static declaration are inaccessible, because static is called directly when the object is not instantiated, and other properties must be called after the object is instantiated. code blockcode blocks refer to a piece of code enclosed in {}, which can be divided into four different locations depending on the location: ordinary blocks of code, building blocks, static blocks of code, synchronized blocks of code, where the synchronous code block involves multithreading. common code blocks: blocks of code that are directly defined in a method are called ordinary blocks of code.
public class Codedemo01{public static void Main (String args[]) {{//plain code block int x = 30;//is a local variable System.out.println ("Normal code block -X = "+ X";} int x = 100;//is the same as the local variable name System.out.println ("Outside the code block--X =" + x);}};


Building Blocks: A code block is defined directly in a class, which is called a building block.
Class Demo{{//writes a block of code directly in the class, called the building Block System.out.println ("1, building block. ") ;} Public Demo () {//define construction Method System.out.println ("2, constructor method. ") ;}}; public class Codedemo02{public static void Main (String args[]) {new demo ();//Instantiate Object new Demo ();//Instantiate Object new Demo ();//Instantiate to Like}};


The construction block takes precedence over the construction method execution and executes multiple times: As soon as an instance object is generated, the constructed content is executed. Static code blocks: blocks of code declared with the static keyword directly are called static blocks of code.
Class Demo{{//writes a block of code directly in the class, called the building Block System.out.println ("1, building block. ") ;} static{//uses static, called Static code block System.out.println ("0, Static code block");} Public Demo () {//define construction Method System.out.println ("2, constructor method. ") ;}}; Public class codedemo03{static{//defines the static block System.out.println ("code block defined in the class where the Main method resides") in the class where the main method resides;} public static void Main (String args[]) {new demo ();//Instantiate Object new Demo ();//Instantiate Object new Demo ();//Instantiate Object}};


Static blocks take precedence over the Main method execution, if the static blocks defined in the normal class take precedence over the construction block execution, regardless of how many instantiation objects are produced, the static code block executes only once, and the primary function of the static block is to initialize the static property. For example, the ability to perform certain operations is achieved without using the main method.
public class Codedemo04{static{system.out.println ("Hello world!!!"); System.exit (1);//Program Exit}};



Object-oriented foundation--static use of keywords and code blocks

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.