编程知识 cdmana.com

The function of static keyword in Java

static The role of keywords

1、 Static member variables are syntactically specific
2、 Static functions are syntactically specific
3、 The syntax of static code blocks is specific

Defining static member variables
Person.java

class Person{
static int a;
}

It can be called as before

public class Test1{
public static void main(String[] args){
Person person = new Person();
person.a = 10;
System.out.println(person.a);
}
}

The output is 10.

add static It can also be used after :

public class Test1{
public static void main(String[] args){
Person.a = 10;
System.out.println(Person.a);
}
}// Join in Java Development and exchange :756584822 Blow water and chat together 

The output is 10.

The difference between a normal member object and a static member variable

Ordinary member variables correspond to p1 and p2 They don't influence each other . And static member variables ,p1 and p2 Using the same variable .
 Insert picture description here

Static functions
Non static member variables cannot be referenced directly in static functions , Cannot be used in static functions this.

Define static functions

Person.java:

class Person{
static void fun(){
System.out.println("static function");
}
}

Test1.java

public class Test1{
public static void main(String[] args){
Person.fun();
}// Join in Java Development and exchange :756584822 Blow water and chat together 
}

Output :static function

Static code block

Static code blocks are executed when the class is loaded , Action is the initial variable .

static{
System.out.println("static code");
}

版权声明
本文为[Java shark]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224152603246K.html

Scroll to Top