java关键字static

static keyword in Java is used a lot in java programming. Java static keyword is used to create a Class level variable in java. static variables and methods are part of the class, not the instances of the class.

Java中的static关键字在Java编程中经常使用。 Java static关键字用于在Java中创建类级别的变量。 静态变量和方法是类的一部分,而不是类的实例。

Java中的static关键字 (static keyword in java)

Java static keyword can be used in five cases as shown in below image.

如下图所示,可以在五种情况下使用Java静态关键字。

We will discuss four of them here, the fifth one was introduced in Java 8 and that has been discussed at Java 8 interface changes.

我们将在这里讨论其中的四个,第五个是在Java 8中引入的,并且已经在Java 8接口更改中进行了讨论。

  1. Java静态变量 (Java static variable)

    We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class.

    Since static variables are shared across all the instances of Object, they are not thread safe.

    Usually, static variables are used with the final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it with ClassName.variableName

    //static variable exampleprivate static int count;public static String str;public static final String DB_USER = "myuser";

    我们可以在类级别的变量中使用static关键字。 静态变量是类变量,不属于该类的对象/实例。

    由于静态变量在Object的所有实例之间共享,因此它们不是线程安全的 。

    通常,静态变量与final关键字一起使用,以表示所有对象都可以使用的公共资源或常量。 如果静态变量不是私有变量,则可以使用ClassName.variableName进行访问

  2. Java静态方法 (Java static method)

    Same as static variable, static method belong to class and not to class instances.

    A static method can access only static variables of class and invoke only static methods of the class.

    Usually, static methods are utility methods that we want to expose to be used by other classes without the need of creating an instance. For example Collections class.

    Java Wrapper classes and utility classes contains a lot of static methods. The main() method that is the entry point of a java program itself is a static method.

    //static method examplepublic static void setCount(int count) {if(count > 0)StaticExample.count = count;}//static util methodpublic static int addInts(int i, int...js){int sum=i;for(int x : js) sum+=x;return sum;}

    From Java 8 onwards, we can have static methods in interfaces too. For more details please read Java 8 interface changes.

    与静态变量相同,静态方法属于类,而不属于类实例。

    静态方法只能访问类的静态变量,并且只能调用类的静态方法。

    通常,静态方法是我们希望公开的实用程序方法,供其他类使用,而无需创建实例。 例如Collections类 。

    Java包装程序类和实用程序类包含许多静态方法。 作为Java程序本身入口点的main()方法是静态方法。

    从Java 8开始,我们也可以在接口中使用静态方法。 有关更多详细信息,请阅读Java 8接口更改 。

  3. Java静态块 (Java static block)

    Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader.

    Static block is used to initialize the static variables of the class. Mostly it’s used to create static resources when the class is loaded.

    We can’t access non-static variables in the static block. We can have multiple static blocks in a class, although it doesn’t make much sense. Static block code is executed only once when the class is loaded into memory.

    static{//can be used to initialize resources when class is loadedSystem.out.println("StaticExample static block");//can access only static variables and methodsstr="Test";setCount(2);}

    Java静态块是由Java ClassLoader将类加载到内存中时执行的语句组。

    静态块用于初始化类的静态变量。 通常,它用于在加载类时创建静态资源。

    我们无法在静态块中访问非静态变量。 我们可以在一个类中有多个静态块,尽管这没有多大意义。 当类加载到内存中时,静态块代码仅执行一次。

  4. Java静态类 (Java Static Class)

    We can use static keyword with nested classes. static keyword can’t be used with top-level classes.

    A static nested class is same as any other top-level class and is nested for only packaging convenience.

    Read: Java Nested Classes

    我们可以对嵌套类使用static关键字。 static关键字不能与顶级类一起使用。

    静态嵌套类与任何其他顶级类相同,并且仅出于包装方便而嵌套。

    阅读: Java嵌套类

Let’s see all the static keyword in java usage in a sample program.

让我们在示例程序中查看Java用法中的所有static关键字。

StaticExample.java

StaticExample.java

package com.journaldev.misc;public class StaticExample {//static blockstatic{//can be used to initialize resources when class is loadedSystem.out.println("StaticExample static block");//can access only static variables and methodsstr="Test";setCount(2);}//multiple static blocks in same classstatic{System.out.println("StaticExample static block2");}//static variable exampleprivate static int count; //kept private to control its value through setterpublic static String str;public int getCount() {return count;}//static method examplepublic static void setCount(int count) {if(count > 0)StaticExample.count = count;}//static util methodpublic static int addInts(int i, int...js){int sum=i;for(int x : js) sum+=x;return sum;}//static class example - used for packaging convenience onlypublic static class MyStaticClass{public int count;}}

Let’s see how to use static variable, method and static class in a test program.

让我们看看如何在测试程序中使用静态变量,方法和静态类。

TestStatic.java

TestStatic.java

package com.journaldev.misc;public class TestStatic {public static void main(String[] args) {StaticExample.setCount(5);//non-private static variables can be accessed with class nameStaticExample.str = "abc";StaticExample se = new StaticExample();System.out.println(se.getCount());//class and instance static variables are sameSystem.out.println(StaticExample.str +" is same as "+se.str);System.out.println(StaticExample.str == se.str);//static nested classes are like normal top-level classesStaticExample.MyStaticClass myStaticClass = new StaticExample.MyStaticClass();myStaticClass.count=10;StaticExample.MyStaticClass myStaticClass1 = new StaticExample.MyStaticClass();myStaticClass1.count=20;System.out.println(myStaticClass.count);System.out.println(myStaticClass1.count);}}

The output of the above static keyword in java example program is:

在Java示例程序中,上述static关键字的输出为:

StaticExample static block
StaticExample static block2
5
abc is same as abc
true
10
20

Notice that static block code is executed first and only once as soon as class is loaded into memory. Other outputs are self-explanatory.

请注意,静态块代码首先执行,并且仅在类加载到内存后才执行一次。 其他输出是不言自明的。

Java静态导入 (Java static import)

Normally we access static members using Class reference, from Java 1.5 we can use java static import to avoid class reference. Below is a simple example of Java static import.

通常,我们使用类引用访问静态成员,从Java 1.5开始,我们可以使用Java静态导入来避免类引用。 以下是Java静态导入的简单示例。

package com.journaldev.test;public class A {public static int MAX = 1000;public static void foo(){System.out.println("foo static method");}
}
package com.journaldev.test;import static com.journaldev.test.A.MAX;
import static com.journaldev.test.A.foo;public class B {public static void main(String args[]){System.out.println(MAX); //normally A.MAXfoo(); // normally A.foo()}
}

Notice the import statements, for static import we have to use import static followed by the fully classified static member of a class. For importing all the static members of a class, we can use * as in import static com.journaldev.test.A.*;. We should use it only when we are using the static variable of a class multiple times, it’s not good for readability.

注意import语句,对于静态导入,我们必须使用import static然后再使用类的完全分类的static成员。 为了导入一个类的所有静态成员,我们可以像在import static com.journaldev.test.A.*;那样使用import static com.journaldev.test.A.*; 。 仅当我们多次使用类的静态变量时,才应使用它,这不利于可读性。

Update: I have recently created a video to explain static keyword in java, you should watch it below.

更新 :我最近创建了一个视频来解释Java中的static关键字,您应该在下面观看。

演示地址

翻译自: https://www.journaldev.com/1365/static-keyword-in-java

java关键字static

java关键字static_Java中的static关键字相关推荐

  1. java 释放static_JAVA中的static关键字作用与用法

    static关键字: 一.特点: 1.static是一个修饰符,用于修饰成员.(成员变量,成员函数)static修饰的成员变量称之为静态变量或类变量. 2.static修饰的成员被所有的对象共享. 3 ...

  2. 面试季,Java中的static关键字解析

    点击上方"方志朋",选择"置顶或者星标" 你的关注意义重大! static关键字是很多朋友在编写代码和阅读代码时碰到的比较难以理解的一个关键字,也是各大公司的面 ...

  3. Java中的static关键字详解

    ** Java中的static关键字详解 ** 在一个类中定义一个方法为static,即静态的,那就是说无需本类的对象就可以调用此方法.调用一个静态方法就是 "类名.方法名" ,静 ...

  4. Java中的static关键字解析 转载

    原文链接:http://www.cnblogs.com/dolphin0520/p/3799052.html Java中的static关键字解析 static关键字是很多朋友在编写代码和阅读代码时碰到 ...

  5. [转] Java中的static关键字解析

    Java中的static关键字解析 static关键字是很多朋友在编写代码和阅读代码时碰到的比较难以理解的一个关键字,也是各大公司的面试官喜欢在面试时问到的知识点之一.下面就先讲述一下static关键 ...

  6. 【Java学习笔记之十五】Java中的static关键字解析

    Java中的static关键字解析 static关键字是很多朋友在编写代码和阅读代码时碰到的比较难以理解的一个关键字,也是各大公司的面试官喜欢在面试时问到的知识点之一.下面就先讲述一下static关键 ...

  7. java中的static类_再议Java中的static关键字

    再议Java中的static关键字 java中的static关键字在很久之前的一篇博文中已经讲到过了,感兴趣的朋友可以参考:<Java中的static关键字解析>. 今天我们再来谈一谈st ...

  8. [5] Java中的static关键字

    Java中的static关键字 文章目录 Java中的static关键字 static的基本概念 static修饰类中的成员 static修饰主类中的方法 static修饰类中的方法 static修饰 ...

  9. java static关键字的作用是什么_java中的static关键字

    一.static代表着什么 在Java中并不存在全局变量的概念,但是我们可以通过static来实现一个"伪全局"的概念,在Java中static表示"全局"或者 ...

最新文章

  1. Oracle批量导出AWR报告
  2. 添加linux系统调用的两种方式
  3. 0-1背包 java_0-1背包问题,java的动态规划如题,代码如下public
  4. 《数据结构》知识点Day_04
  5. .NET Core容器化之多容器应用部署@Docker-Compose
  6. ppt生成器_9款魔性#傻瓜生成器#,上班可以划水一天
  7. 如何在MySQL中导入和导出数据库并重置root密码
  8. 第一:Git安装和使用github(超详解)
  9. Java 面向对象编程 tricks
  10. CentOS7 Juno Cinder块重启后 实例起不来 --rescan Exit code: 21
  11. was cached in the local repository, resolution will not be reattempted until the update interval of
  12. 这绝对是目前最好用的电脑桌面便签,免费的,墙裂推荐
  13. PostGis创建空间数据库方法
  14. 一分钟搞懂app热更新
  15. 文本相似度:Distributed Representations of Sentences and Documents
  16. oracle的日期时间转换日期,oracle 的时间日期转换函数
  17. python爬取站酷海洛图片_站酷海洛图片爬取
  18. Reference Counted Smart Pointers
  19. Educoder 机器学习 决策树使用之使用决策树预测隐形眼镜类型
  20. React实现支付宝支付代码

热门文章

  1. python基础_collections系列
  2. Shell 常用积累
  3. php和java的一些比较
  4. 【莫比乌斯反演】[HYSBZ/BZOJ2693]jzptab
  5. [开源]STM32F103RBT6最小系统,LEDx2,KEYx4
  6. 【Git入门之十四】Git GUI
  7. DNS分别在什么情况下使用UDP和TCP?
  8. java项目连接Oracle配置文件
  9. python第八十八天----dom js
  10. document.createElement()的用法