static应用知识:工具类
1、工具类作用
- 内部都是静态方法,每一个方法只完成一个功能
- 一次编写,整个包中各个类都可以调用,提高代码的复用性
2、工具类要求
- 工具类的构造器建议私有化处理
/**
* 工具类
*/
public class Util {
//隐藏构造器
/**
* 注意:由于工具类无需创建对象,所以吧其构造器转化为私有会显得很专业
*/
private Util(){
}
/**
* 静态方法
*/
public static String createVerifyCode(int n){
//开发一个验证码
String code="";
//定义一个变量记住全部验证码字符
String data="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//定义一个循环生辰几个随机索引,去得到几个字符
Random r=new Random();
for (int i = 0; i < n; i++) {
int index=r.nextInt(data.length());//data内随机一个索引对应的字符
code+=data.charAt(index);
}
return code;
}
}
static应用知识:代码块
1、代码块概述:
- 代码块是类的5大成分之一(成员变量、构造器、方法、代码块,内部类),定义在类中方法外
- 在Java类下,使用{}括起来的代码称为代码块
2、静态代码块:static{}
- 特点:通过static关键字修饰,随着类加载而加载,自动触发执行1次,优先于main方法块执行
- 作用:启动系统时对于静态资源进行初始化
- 使用场景:类加载时对于静态数据进行初始化
public class StaticDemo1 {
public static String schoolName;
public static ArrayList<String> cards=new ArrayList<>();
public static void main(String[] args) {
//目标:理解静态代码块
System.out.println("main方法执行");
}
/*
静态代码块:有static修饰,属于类,与类一起优先加载一次,自动触发执行,并且比main方法块先执行
作用:用于初始化静态资源(例如:在线人数,初始化名字)
*/
static {
System.out.println("静态代码块被执行了");
schoolName="njz";
System.out.println(schoolName);
cards.add("3");
cards.add("4");
System.out.println(cards);
}
}
3、构造代码块:{} (实例代码块)
- 特点:无static修饰,属于对象,每次构建对象时,都会触发一次执行,优先于构造器运行
- 使用场景:初始化实例资源
public class StaticDemo2 {
private String name;
public StaticDemo2(){
System.out.println("无参构造器执行");
}
/**
* 实例代码块:无static修饰,属于对象,每次构建对象时,都会触发一次执行,优先于构造器运行
* 初始化实例资源
*/
{
name="njz";
System.out.println("实例代码块已执行");
}
public static void main(String[] args) {
//目标:理解实例代码块
StaticDemo2 s1=new StaticDemo2();
System.out.println(s1.name);
StaticDemo2 s2=new StaticDemo2();
System.out.println(s2.name);
}
}
4、项目:斗地主初始化牌类
public class StaticTest3 {
/**
* 1、定义一个静态的集合,这样这个集合只加载一个,因为当前房间只需要一副牌
* @param args
*/
public static ArrayList<String> cards=new ArrayList<>();
/**
* 2\程序运行main方法前吧54张牌放入,后续游戏就可以继续使用,采用静态代码块
* @param args
*/
static {
//3、正式吧牌放入集合中
//定义一个数组储存全部点数
String value[]={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
//定义一个数组储存全部花色
String colors[]={"♥️","♠️","♦️","♣️"};
//遍历点数
for (int i = 0; i < value.length; i++) {
//遍历花色
for (int j = 0; j < colors.length; j++) {
String card=value[i]+colors[j];
cards.add(card);
}
}
//单独加入大小王
cards.add("小🃏");
cards.add("大🃏");
}
public static void main(String[] args) {
//目标:模拟游戏启动前,初始化54张牌
System.out.println("新牌"+cards);
}