栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java基础--- static关键字

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java基础--- static关键字

Java基础--- static关键字
  • 静态成员 --- Static Fields
  • 静态常量 --- Static Constant
  • 静态方法 --- Static Methods

静态成员 — Static Fields
  • 一个类只有这一个这样的成员实例, 直接用类名调用
  • 即使没有对象实例, 静态成员也存在

Example: 给每个雇员产生unique ID

public void setId() {
	id = nextId;
	nextId++;
}

harry.id = Employee.nextId;
Employee.nextId++;
静态常量 — Static Constant
  • 和静态成员一样, 只不过是常量
public class Math {
 . . .
 public static final double PI = 3.14159265358979323846;
 . . .
}
Math.PI.

Another static constant that you have used many times is System.out. It is declared in the System class as follows:

public class System {
 . . .
 public static final PrintStream out = . . .;
 . . .
}
  • it is never a good idea to have public fields, because everyone can modify them.
  • However, public constants (that is, final fields) are fine. Since out has been declared as final, you cannot reassign another print stream to it: System.out = new PrintStream(. . .); // Error--out is final
静态方法 — Static Methods
  • 静态方法跟类的对象没有关系, 不管有没有对象实例, 静态方法都存在. 也是直接用类名调用
  • 静态方法不能使用非静态成员变量, 但是可以使用静态成员变量

什么时候使用静态方法:

  • 当一个方法不需要使用对象的状态, 也就是所需的参数都是外部直接传入的, 比如: Math.pow
  • 当一个方法使用的都是静态成员变量时
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/856646.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号