Introduction to how static keywords are used in Java

Source: Internet
Author: User

1         Static Methods

Before we learned some of the ways that static member variables are used, let's look at the content of static methods and see how static methods are used.

1.1      methods for defining static methods and general methods

in a class we can define the method of the class, if a keyword is added to the front of a method Static, and when the method uses static modifiers, we call this method a static method, not a keyword, not a static method. as an example of Car class, define a static method stop (), and a non-static method Show (), as shown in the following code.

public class Car {

Publicstring color;

Publicstatic String mycolor= "white";

Car (Stringcolor) {

This.color=color;

}

General Method Show ()

Voidshow (String color,string mycolor) {

System.out.println ("The color of the car is " +color);

}

static method Stop ()

Static Voidstop () {

System.out.println ("The car stopped. ");

}

Public Static void Main (string[] args) {

carcar1=New Car ("Blue");

Car1.show ();

car1.stop ();

Car car2=new car ("yellow");

Car2.show ();

car2.stop ();

}

}

The result of the operation is:

the color of the car is Blue

The car stopped.

the color of the car is yellow

The car stopped.

with the above code, we find that static methods, like normal methods, can be called by objects in addition to static modifiers before static methods. This is the same static method as the general method.

1.2      What is the use of static methods? 1.2.1   static methods do not call member variables

in the there are two methods in the Car class, one method is show (), and the other method is stop (). Assuming that both methods are common, then when defining the object, you need to assign the corresponding memory address space to the two methods.

from the code we can conclude thatshow () accesses the member variable color and the static member variable mycolor, and the Stop () method does not have access to any member variable. That is to give the method show () and Method stop () to allocate memory space while the Method show () allocates memory space and does not have the property to hold the object. Then this memory space is wasted. Specific as shown.

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/83/28/wKiom1dr0SuDybHyAAC93EUQkoo064.jpg "title=" static modifier static3.jpg "alt=" Wkiom1dr0sudybhyaac93euqkoo064.jpg "/>

Figure 1 Defining a general method method after the in-memory usage graph

To solve this wasted memory space, we can add a static modifier to the method before adding a method that does not require access to the member variable, and define it as a static method. The static method only needs to allocate memory space once in memory, and this memory space belongs to the data share, which is different from the object's memory space, and all objects of the class can call the static method. The use of static methods can eliminate the drawbacks of the general method, saving memory space.

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/83/28/wKioL1dr0ffCgnWcAAC-4WXKEwc650.jpg "title=" static modifier static4.jpg "alt=" Wkiol1dr0ffcgnwcaac-4wxkewc650.jpg "/>

Figure 2 defining a static method after the memory space usage graph

1.2.2   calling a method directly in a class

Suppose the object of the class is not built, and how do you want to invoke the method?

We know that the general method needs to build the object before it can invoke the method through the object, which does not reach our requirements. This is the only way to achieve this requirement by using static methods. For example, take the following example.

Public class car {         publicstring color ;          publicstatic string mycolor= "White"; Car () {}car (Stringcolor) {                    this.color=color;         }          //General Method Show ()           voidshow () {                    SYSTEM.OUT.PRINTLN ("The color of the car is" +this.color);          }         //static method Stop () static voidstop ()  {                     system.out.println ("The car stopped. ");         }          Publicstatic void main (String[] args)  {                    newcar (). Stop ();          }}

The result of the operation is:

The car stopped.

We found no build object, but succeeded in invoking a static method. Without building objects, you do not need to allocate memory space to objects, so using classes to invoke static methods also achieves the effect of saving memory space.

1.3     is it possible that any method can be defined as a static method?

static methods save memory, is it not all methods are defined as static methods to save memory space? Or take the Car class as an example, define the show () method as a static method to see what happens.

Public class car {         publicstring color ;          publicstatic string mycolor= "White"; Car () {}car (Stringcolor) {                    this.color=color;         }          //static method Show ()           staticvoid show () {                    SYSTEM.OUT.PRINTLN ("The color of the car is" +color);          }         //static method Stop () Static voidstop ()  {                    SYSTEM.OUT.PRINTLN ("Car stopit down. ");         }          publicstatic void main (String[] args)  {                    newcar (). Show (); New Car (). Stop ();          }}

Compile, Discovery will error

Error Content: Cannot make astatic reference to the Non-static field color.

this is because a non-static variable color is called in the Show () method,and static methods can only invoke static variables, so an error is made.

If we modify the code in the Show () method, change to the following:

Static void Show () {

System. out. println ("The color of the car is " +mycolor);

}

The result of the operation is:

the color of the car is white

The car stopped.

After we replace the variable accessed in the Show () method with a static member variable, we find that it can be compiled and run correctly.

If we modify the code in the Show () method, change to the following:

Static void Show () {

System. out. println ("The color of the car is " +this.mycolor);

}

compile, the discovery will error.

Error Content: Cannotuse this in a static context

It can be concluded that not all methods can be defined as static methods, only methods that do not access member variables or access static member variables can be defined as static methods, and methods that do not use the This keyword can be defined as static methods.

why can't static methods access non-static member variables? This is because static methods are loaded with the load of the class, and the static methods are first associated with the objects in memory and cannot be accessed after the properties and methods in the object, so static methods cannot access non-static methods or variables. Static variables are loaded as the class loads, so static methods can access static variables.

Why can't I use the This keyword in a static method ? This is because the This keyword is a pointer to an object's address, and when a static method is called using a class, there is no object generated, so the This keyword will appear to be ambiguous, so the static method in Java cannot be used the This keyword.

1.4    who can call static methods?

after you define a static method, you can call a static method. So who can call static methods? In front we used "new Car". Stop (); statement to call the static method stop (), which indicates that a static method can be called using a class.

1.4.1   object calls a static method

A static method is also one of the methods, can you call a static method using an object? We use the following code to illustrate:

Public class car {         publicstring color ;          publicstatic string mycolor= "White"; Car () {}car (Stringcolor) {                    this.color=color;         }          //General Method Show ()           voidshow () {                    SYSTEM.OUT.PRINTLN ("The color of the car is" +color);          }         //static method Stop () static voidstop ()  {                     System.out.println ("The car stopped. ");          }          Publicstatic void main (String[] args)  {                    carcar=new car ();                    car.stop ();          }}

The results of the operation are as follows:

The car stopped.

based on the result of the operation, we can conclude that the object may call the static method directly.

1.2.2   static methods called by non-static methods

Can a static method be called by a non-static method? Let's use the following code for example.

Public class car {         publicstring color ;          publicstatic string mycolor= "White"; Car () {}car (Stringcolor) {                    this.color=color;         }          //General Method Show ()           voidshow () {                    SYSTEM.OUT.PRINTLN ("The color of the car is" + mycolor);                    stop ();          }         //static method Stop () static  Voidstop ()  {   &Nbsp;                System.out.println ("The car stopped. ");         }          publicstatic void main (String[] args)  {                    carcar=new car ();                    car.show ();          }}

The results of the operation are as follows:

the color of the car is white

The car stopped.

by running the results we can conclude that the non-static method Show () successfully called the static method stop ().

from the above examples, we conclude that class, object, and non-static methods are able to invoke static methods successfully.


This article is from "Rookie Advanced" blog, please be sure to keep this source http://zyejl.blog.51cto.com/2769851/1792335

Introduction to how static keywords are used in Java

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.