欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java final 关键字理解 博客分类: Java  

程序员文章站 2024-02-18 19:56:40
...


public class TestFinal {
    private static final String name = "testName";
    private static final Person person = new Person("Test person name",18);
    public static void main(String[] args) {
        System.out.println("TestFinal.name:"+TestFinal.name);
        //The final field TestFinal.name cannot be assigned
        //TestFinal.name = "Test Name Change";
        System.out.println("TestFinal.person.getName():"+TestFinal.person.getName());
        System.out.println("TestFinal.person.getAge():"+TestFinal.person.getAge());
        TestFinal.person.setName("Test person name changed");
        TestFinal.person.setAge(20);
        System.out.println("After changed value TestFinal.person.getName():"+TestFinal.person.getName());
        System.out.println("After changed value TestFinal.person.getAge():"+TestFinal.person.getAge());

    }
}

class Person{
    private String name;
    private int age;
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
   
}
/*运行后为:

TestFinal.name:testName
TestFinal.person.getName():Test person name
TestFinal.person.getAge():18
After changed value TestFinal.person.getName():Test person name changed
After changed value TestFinal.person.getAge():20

*/