java之static用法
来源:互联网 发布:约瑟夫环C语言数组实现 编辑:程序博客网 时间:2024/06/04 18:34
需要注意的是 静态属性和方法属于类方法,加载类后,就已经存在静态属性和方法,实例是需要用new构造出来后 才会有引用根据先后顺序,就有以下两条规则1、非静态的方法可以调用静态的或者非静态的属性和方法;2、静态的方法不可以调用非静态的属性和方法,因为非静态的还不一定存在,只能先构造出来后,再通过实例引用例如 在main方法中 可以直接调用static 的方法,调用非static方法 需要先构造出类的实例,通过实例才能调用方法
class Poker{public static final int MAX = 52;
public static Card[] card = new Card[MAX];
//静态可以访问静态的
for(int i = 0; i < 4; i++){
for(int j = 0; j < 13; j++){
card[i*13+j] = new Card(i, j);
}
}
}
public static void printpoker(){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 13; j++){
System.out.print(card[i*13+j].toString()+",");
}
System.out.println();
}
}
//非静态的可以访问静态的;
for(int i = 0; i < 200; i++){
int point_x = (int)(Math.random()*MAX);
int point_y = (int)(Math.random()*MAX);
Card temp =card[point_x];
}
}
}
这样的代码不会错误,下面的是错误的代码:
class Poker{
public static final int MAX = 52;
Card[] card = new Card[MAX];
//静态不能访问非静态
public static void initpoker(){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 13; j++){
card[i*13+j] = new Card(i, j);
}
}
}
public static void printpoker(){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 13; j++){
System.out.print(card[i*13+j].toString()+",");
}
System.out.println();
}
}
//非静态可以访问非静态
void wash(){
for(int i = 0; i < 200; i++){
int point_x = (int)(Math.random()*MAX);
int point_y = (int)(Math.random()*MAX);
Card temp =card[point_x];
}
}
}
- java之static用法
- java之static用法
- Java之static用法(详解)
- Java之static用法(详解)
- java之static关键字用法
- Java之static的用法
- C++之static用法 .
- JavaSE之static用法
- java的static用法
- Java中static用法
- java的static用法
- java的static用法
- java的static用法
- JAVA中的static用法
- Java中static用法
- java的static用法
- Java static 用法
- java static的用法
- Using canvas to do bitmap sprite animation in JavaScript
- 云中的angel:汪涵推介手机QQ浏览器
- Error starting modern compiler
- phonegap+Android实现内容溢出滚动条Scroll bar的功能!
- Java基础20天--05--IO流
- java之static用法
- 数据库测试规范
- 几道华为面试题
- PICC编译警告
- 关于 BT及PT
- HttpClient4基础2--通过认证代理访问网页
- 后天播放
- flash游戏资源的国际化
- [IT最前沿--有点强大] 都市圈实时公交:一款实时查询公交到站信息的应用