java中static和final关键字是经常用到的关键字,在日常开发中用起来也非常方便,以下是对static关键字和final关键字的简单、直白、容易理解、非常浅显的解释。
static学名叫“静态修饰符”。什么作用呢?
用static修饰的变量或方法,在类被加载时就被初始化了,就已经存在了,并且它们是在main()方法之前就被初始化了。而非static变量或方法,在对象new出来的时候被初始化的。
好像又变复杂了。直白点:
就是用static修饰的变量、方法,在使用它们时,不需要进行实例化即可使用,使用的方法就是 类名.变量。
看例子:
public class StaticAndfinal {
//这是被static修饰的一个字符串
public static String stastr="this is static str!";
}
使用它:
public class StaticAndFinalMain {
public static void main(String[] args) {
//1.在这里我们没有对类StaticAndfinal进行实例化,就可以直接使用这个类的static变量。
System.out.println(StaticAndfinal.stastr);
//2.这个static变量是可以改变的。
StaticAndfinal.stastr="this is new staticstr";
System.out.println(StaticAndfinal.stastr);
}
}
运行:
请注意:static修饰的字符串是可以改变的。
同样,static的方法一样的道理,但是static的方法在使用时需要考虑线程安全性问题,因为static方法在内存中只有一份,而非static方法跟随对象自己是自己的。
final1.final修饰变量时:
意味着这个变量不可改变,在哪里都不能变,就叫它常量。如java.lang.Math类中的PI和E是final成员,其值为3.141592653589793
看例子:
public class StaticAndfinal {
//这是被static修饰的一个字符串
public static String stastr="this is static str!";
//这是被final修饰的一个字符串
public static final String finstr="this is static final str!";
}
尝试改变它:
public class StaticAndFinalMain {
public static void main(String[] args) {
//1.在这里我们没有对类StaticAndfinal进行实例化,就可以直接使用这个类的static变量。
System.out.println(StaticAndfinal.stastr);
//2.这个static变量是可以改变的。
StaticAndfinal.stastr="this is new staticstr";
System.out.println(StaticAndfinal.stastr);
//3.尝试改变一下final修饰的变量
StaticAndfinal.finstr="want to change finstr";
}
}
报错了:
2.final修饰方法时:
【过年好!年后见】
3.final修饰类时:
【过年好!年后见】