java直白解释,关于java的static和final关键字的直白、简单解释

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);

}

}

运行:

ea2805b1f1dcfc34121cf7bf2bf56cdc

请注意: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";

}

}

报错了:

5ad39e067dae10ac641ab26de9395472

2.final修饰方法时:

【过年好!年后见】

3.final修饰类时:

【过年好!年后见】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值