注册 登录
编程论坛 JAVA论坛

java关于final的疑惑

娱乐 发布于 2021-02-21 13:32, 1916 次点击
public class H {
    public static void main(String []args) {
       final H h =new H();
        H g =new H();
    }
}

有无final有什么区别?
3 回复
#2
tequilashou2021-02-21 16:22
回复 楼主 娱乐
第一次没有final  可以继续new 对象 对象的内存地址为一致

程序代码:
@Test
    void test() {
        
        
        Info info=new Info(18,"张三",18);
        
        
        System.out.println("第一次info的值==="+info);
        System.out.println("第一次info的内存地址==="+info.hashCode());
        
        info=new Info();
        
        info.setId(20);
        info.setName("李四");
        info.setAge(28);
        
        
        
        System.out.println("修改后info的值==="+info);
        System.out.println("修改后info的内存地址==="+info.hashCode());
        
        
    }

}
#3
tequilashou2021-02-21 16:23
回复 2楼 tequilashou
第二次 加了final 直接代码报错,不允许在final 修饰下创建对象

程序代码:
package java_demo;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;

import spring.model.Info;

class javaTest {

    @Test
    void test() {
        
        
        final Info info=new Info(18,"张三",18);
        
        
        System.out.println("第一次info的值==="+info);
        System.out.println("第一次info的内存地址==="+info.hashCode());
        
        info=new Info();
        
        info.setId(20);
        info.setName("李四");
        info.setAge(28);
        
        
        
        System.out.println("修改后info的值==="+info);
        System.out.println("修改后info的内存地址==="+info.hashCode());
        
        
    }

}
#4
gennzhang2021-02-24 20:07
被final修饰的变量h不能再赋值了。
程序代码:
public class H {
    public static void main(String []args) {
        final H h = new H();
        h = new H(); // 这里报错
        H g = new H();
    }
}

错误: 无法为最终变量h分配值
        h = new H();
        ^
1