您的位置:首页 > 编程语言 > Java开发

Java static

2016-04-18 11:26 381 查看
static
 members
belong to the class instead of a specific instance.

It means that only one instance of a 
static
 field
exists[1] even if you create a million instances of the class or you don't create any. It will be shared by all instances.

Since 
static
 methods
also do not belong to a specific instance, they can't refer to instance members (how would you know which instance Hello class you want to refer to?). 
static
 members
can only refer to 
static
 members.
Instance members can, of course access 
static
 members.

Side note: Of course, 
static
 members
can access instance members through an object reference.

Example:
public class Example {
private static boolean staticField;
private boolean instanceField;
public static void main(String[] args) {
// a static method can access static fields
staticField = true;

// a static method can access instance fields through an object reference
Exam
4000
ple instance = new Example();
instance.instanceField = true;
}


[1]: Depending on the runtime characteristics, it can be one per ClassLoader or AppDomain or thread, but that is beside the point.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: