final数据成员和static final 数据成员的区别

    xiaoxiao2025-01-09  10

    <span style="color: rgb(51, 51, 51); font-family: Helvetica, Tahoma, Arial, sans-serif; font-size: 14px; line-height: 24px; background-color: rgb(245, 245, 245);">此区别只有在运行期内被初始化时才会显现,这是因为编译器对编译期数值一视同仁。当你运行下面的程序时,就会看到这个区别。定义为final,只说明它是一个常量,每次创建对象时都初始化为不同的常量。而定义为  static final 是恒定初始值(即编译期常量),在装载时已被初始化,不可以通过创建新对象而加以改变。</span> public class C { static Random rand = new Random(); final int I=rand.nextInt(20); static final int X=rand.nextInt(20); public String toString(){ return "I="+I+"X="+X; } public static void main(String[] args){ // System.out.println("I="+I+"X="+X);//Error:change I to static C c1 = new C(); C c2 = new C(); System.out.println( c1.toString()); System.out.println( c2.toString()); } } 运行上面的程序输出:I=19X=10 I=16X=10 显然,当创建不同的对象时,非static数据变化了,而static数据没变
    转载请注明原文地址: https://ju.6miu.com/read-1295308.html
    最新回复(0)