为什么工具类中的方法不用实例方法做?
1.实例方法需要创建对象调用
2.此时用对象只是为了调用方法,这样只会浪费内存。
工具类定义时的其他要求:
由于工具里面都是静态方法,直接用类名即可访问,因此,工具类无需创建对象,建议将工具类的构造器进行私有
public class ItYxg{
private ItYxg(){
}//***将构造器私有化!!***
/*静态方法
*/
public static String createVerifyCode(int n){
//开发一个验证码
String code = "";
String date="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789";
Random r = new Random();
for (int i = 0; i < n; i++) {
int index = r.nextInt(date.length());
code+= date.charAt(index);
}
return code;
}
}
静态代码块:
格式:static{}
特点:需要通过static关键字修饰,随着类的加载而加载,并且自动触发、只执行一次。
使用场景:在类加载的时候做一些静态数据初始化的操作,以便后续使用。
例
public static String schoolName;
public static ArrayList<String> cards = new ArrayList<>();
static {
System.out.println("静态代码块被执行了!");
schoolName="xzit";
cards.add("K");
}
实例:初始化斗地主的54张牌
import java.util.ArrayList;
public class staticTest {
/*
1.定义一个静态集合,这样这个集合只加载一次,因为一个房间只需要一副牌
*/
public static ArrayList<String> cards = new ArrayList<>();
/*
2.在程序真正运行main方法前把54张牌放进去,后续游戏可以直接使用。
*/
static {
//3.做牌放到集合中去。
//定义一个数组存储全部点数:类型确定了,数量确定了
String[] sizes = {"3","4","5","6","7","8","9","10","J","Q","K"};
//定义一个数组存储全部花色
String[] colors = {"♥","♦","♣","♠"};
//遍历点数
for (int i = 0; i < sizes.length; i++) {
for (int j = 0; j < colors.length; j++) {
String card = sizes[i]+colors[j];
cards.add(card);
}
}
//单独加入大小王
cards.add("小🃏");
cards.add("大🃏");
}
public static void main(String[] args) {
//模拟斗地主游戏启动前初始化54张牌
System.out.println("新牌:"+cards);
}
}