JAVA: Lesson 9 (keyword 2 static), java keyword static

Source: Internet
Author: User

JAVA: Lesson 9 (keyword 2 static), java keyword static
Keyword 2: static)


Features:
Static is used to modify members (member functions and member functions)

The existence of static takes precedence over the existence of objects and is loaded with the loading of classes.

Static modified members are shared by all objects.

Static can be called directly by class name. Format: System. out. println (Person. country);: Class Name. static member

Usage Details

Static methods can only access static members, I .e. static modified members, static int data;

Static methods cannot write this, super: this represents the object that is currently calling this method.

The main function (main) is static: public static void main (String [] args)


Import java. util. export; import javax. naming. ldap. sortControl; class Person {String name; // member variable/instance variable static String country = "CN"; // static variable/class variable public void show () {System. out. print (country + ":" + name) ;}} public class Main {public static void main (String [] args) {Person BLF = new Person (); cin = new partition (System. in); // BLF. name = cin. nextLine (); BLF. name = "BLF2"; BLF. show (); System. out. println (Person. country); // static sharing, which can be output directly using the class name // but cannot be abused. Some data is unique after all, not shared // such as Chinese, and the nationality is shared, however, the name is a unique cin. close ();}}


Differences between member variables and static variables:


1. The two have different lifecycles. Long static Lifecycle


A member variable exists with the creation of the object and is released with the release of the object. That is, the existence of the member variable depends on the existence of the object.
Static variables are loaded with the class and disappear as the class disappears.


2. Different call Methods
Member variables can only be called by objects
Static variables can be called by objects and can be called by class names. Therefore, it is best to call static variables with class names. They are clear and do not need to be created.

3.
A member variable is called an instance variable.
Static variables are called class variables.


4. Different storage locations
Member variables are stored in heap memory objects, so they are also called object-specific data (the heap cannot put variables, but only objects, and objects can have variables)
Static variable data is stored in the static zone in the method zone (Data zone/sharing zone), so it is also called the shared data of objects.


Static Usage Details:


1. Access Restrictions: static modification methods can only access static modified members.


Error code:
Import java. util. export; import javax. naming. ldap. sortControl; class Person {String name; static String country = "CN"; public static void show () {System. out. print (country + ":" + name); // because there is no static modifier member name // System. out. print (country + "); // so no name} public class Main {static int data = 9; public static void main (String [] args) {Person BLF = new Person (); condition cin = new condition (System. in); // BLF. name = cin. nextLine (); BLF. name = "hello"; BLF. show (); cin. close ();}}

Therefore, static modified members can be called directly using class names without objects. Because the object does not exist, the name does not exist.
(Non-static can access both static and non-static)



2. The main function is static.

Public class Main {static int data = 9; // static modifier member variable public static void main (String [] args) {show ();} public void show () // if you want to call it here, you must use the static modification method. data is not static and is called Special data // public static void show () // This method can access static modified data {System. out. println (data );}}

To access special data, you can use an object to call the show method.

Public class Main {int data = 9; // static modifier member variable public static void main (String [] args) {Main BLF = new Main (); BLF. show ();} public void show () {System. out. println (data); // It can also be System. out. println (Main. data); // Main. can be omitted }}

Therefore, the main function is used to direct other object work, encapsulate the code into the function, and then encapsulate the function into each class. The main only needs to create such an object, so that the object can work.


Main function parsing:


1: The format is fixed.
2. recognized and used by jvm


Public
Static does not require objects. You can directly use the class name to which the main function belongs.


Void has no return value
Main: a fixed name recognized by jvm, not a keyword.
String [] args: a parameter list of the main function. It is an array-type parameter and is of the struct type.

Import java. util. extends; public class Main {public static void main (String [] args) {using cin = new using (System. in); System. out. println (args); // print [Ljava. lang. string; @ 7d4991ad }}

If there is an address, it indicates that there is an entity. Its length is:

Import java. util. extends; public class Main {public static void main (String [] args) // => new String [0] {using cin = new using (System. in); System. out. println (args. length); // print 0 }}

An array object is generated, but nothing is stored. When running a program in java: You can pass specific parameter values. You can pass the required parameters at the program entry, A string can be converted to another type regardless of whether it is a string.


Of course, args is the only thing that can be changed. However, it has become a habit. In the early days, arguments: Parameter

import java.util.Scanner;public class Main{public static void main (String[] args) {Scanner cin = new Scanner(System.in);for(int i = 0;i<args.length;i++){System.out.println(args[i]);}System.out.println(args.length);}}

The running diagram is as follows:



Of course, you can write it in this format:


Import java. util. program; public class Main {public static void main (String [] args) // program entry {program cin = new program (System. in); int x = 10; main (x);} public static void main (int x) // reload {System. out. println (x );}}

Memory loading:





When is static used?

Static modifier, which can only modify members (member variables and member functions)

1. static member variables
Without static, the object is exclusive. If static is added to the method area, the object is shared.
The object is in heap memory. When the values of the same member variables in multiple objects are the same, there is no need to store each object,
This member value can be extracted and modified using static (for the effective use of space). However, if an object
If the values of variables are different, the object's special value cannot be modified using static instead of static.


2. Static Functions

Whether the function is static (that is, whether the function can be directly called by class or directly called by object ), the key is to check whether the function has the special data of the object, that is, whether the function needs to access non-static member variables. If necessary, it can be defined as non-static. If you do not need it, you can define it as static. Of course, it can also be non-static. However, if the method does not access special data, you do not need to create an object. Instead, setting up an object wastes memory, use the class name directly.


Error Code Demo: Access static variables

Import java. util. extends; class MAN {static int num = 5; int age; public void show () // without static // so add public static void show () {System. out. println (num) ;}} public class Main {public static void main (String [] args) {MAN. show (); // error }}



To access special data, you must have an object.

Import java. util. extends; class MAN {static int num = 5; int age; public void show () // No static {System. out. println (age) ;}} public class Main {public static void main (String [] args) {MAN. show (); // error new MAN. show ();}}


Static code block:

When the class is loaded and executed only once, that is, when the class is referenced for the first time

Role: static code blocks are used to initialize classes (constructors initialize objects)

import java.util.Scanner;class MAN{static {       System.out.println("BLF");} void show(){System.out.println("BLF2");}}1.public class Main{public static void main (String[] args) { new MAN().show();}}//BLF//BLF2
2. public class Main {public static void main (String [] args) {new MAN (). show (); new MAN (). show () ;}// BLF // BLF2 // The BLF2 class already exists.

The static code block assigns an initial value to the class.

class MAN{static int num ;static {       num = 9;       num *=2;}static void show(){System.out.println(num);}}public class Main{public static void main (String[] args) { MAN.show(); MAN jo = new MAN(); jo.show();}}


There are not many static code blocks. Generally, this class is static and uses static code blocks.

Public class Main {static {System. out. println ("a");} public static void main (String [] args) {System. out. println ("B") ;}} print that the main function of a B is called before execution.







Static keyword in JAVA

Static is a java keyword and also a keyword for static modification. variables or methods modified using this keyword can be called directly through the class name, for example:
Public class {
Static int a = 10;
}
Class B {
Int B = a. a; // because the integer variable of Class a is modified using static, it can be called by class name.
}

One advantage of this is that you do not need to create a new class, which can save a lot of space for the memory. Variables modified by static are called member variables and member variables are called global variables, the static method is called the member method.

Significance of the static keyword in java

This is a bit like the concept of "global.

Public class MyClass {
Public static void aStaticMethod () {...}; // static method
Public void aNonStaticMethod () {...}; // non-static method
...
}
When you define a class, if the method or variable in it is defined as static, then this method or function only has one object for this class, so it can be referenced and accessed using the class name, for example, MyClass. aStaticMethod ()

Instead of static methods or variables, you must create a new object for this class. For example, the non-static method above must use new MyClass (). aNonStaticMethod ().

This is easy to understand.
For example, if you buy a car of a certain brand, your car should create an object for the car of this brand. It should be a non-static method for you to drive and repair your own car.
The car repair shops on the street are public for all the cars of your brand. Their Car Repair and car washing methods should be static.

In addition, there are some rules. For example, static methods cannot contain non-static methods, but static methods can be used in non-static methods. In this case, I will learn more about them.

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.