On the usage and benefits of the Java static keyword _java

Source: Internet
Author: User

In this paper, the Java static keyword for the use of the summary for your reference, the specific contents are as follows

1. For the use of the static keyword when the modifier variable, it is equivalent to a global variable;

2. When the static modifies a function, he is first loaded by the class when the class is loaded, and can only be loaded once, and this method may not need to be invoked through an instance, for example:

Mystatic.java

Package study;
 
public class Mystatic {public
  static int sta=0;
  public int st=0;
  The static method takes precedence over the use of
  static{
    System.out.println ("some Static");
  }
  Created Mystatic method public
  static void Mystatic () {
    System.out.println ("static");
  }
  Public mystatic () {
    System.out.println ("mystatic");
  }
  public void Demo () {
    System.out.println ("demo");
  }

Test.java

Package study;
 
public class Test {public
  static void Main (string[] args) {
     
     
    mystatic my=new mystatic ();
    int demo=my.st;//Create object call non-static variable
    my.demo ();//Create Object call non-static function
    mystatic.mystatic ();//You can call static methods directly;
    int a= mystatic.sta;//can directly call the static variable
    //int b=mystatic.st; This will be an error, because the object was not created in advance
  }
}

Results:

Some static
mystatic
demo
static

For this result, the static method is called preferentially when the Mystatic class is created, and then calls the constructor method before invoking the other methods.

The above is the entire content of this article, I hope to help you learn.

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.