1.static定义的静态方法里面不能引用非静态的变量。
比如以下代码中的变量s在encrypt里面引用的时候会报:
Non-static field 's' can not be referenced from a static context.
public class AESUtil {
private String s = "abc";
/**
* 加密
*
* @param content 需要加密的内容
* @param password 加密密码
* @return
*/
public static String encrypt(String content, String password) {
System.out.println(s);
try {
byte[] raw = password.getBytes("UTF-8");
SecretKeySpec key = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return parseByte2HexStr(result); // 加密
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
被static修饰的方法或者变量,在内存中只有一个拷贝,jvm只为静态变量分配一次内存,是在加载类的过程中分配的。
对于实例变量,每创建一个实例就会分配一个内存。
声明为static的方法有以下几条限制:
• 它们仅能调用其他的static方法。
• 它们只能访问static数据。
• 它们不能以任何方式引用this或super(关键字super 与继承有关,在下一章中描述)。
问题:为什么static方法不能调用实例变量呢?
网友评论