为什么标记为final的对象可以在Java中修改并调用非final方法? 我是java新手,我是C++背景的。 C++中的代码> >最终< /代码>,就像C++中的代码> const < /c> >,但我想不是. 对象在C++中被初始化为 const ,只能调用 const 方法,并且不能更改对象中的字段。

为什么标记为final的对象可以在Java中修改并调用非final方法? 我是java新手,我是C++背景的。 C++中的代码> >最终< /代码>,就像C++中的代码> const < /c> >,但我想不是. 对象在C++中被初始化为 const ,只能调用 const 方法,并且不能更改对象中的字段。,java,android,immutability,final,Java,Android,Immutability,Final,但在下面的代码中,我可以在pet中赋值。i、 e.pet.id=newobjectid(newPetId) 在Java中,关键字“final”只是表示一旦初始化,就不能更改变量的值。 比如说, final int x = 0;` //You can't do this!!! int x=5 与变量调用方法无关。< P>引用埃里克的评论中的回答,我找到了C++程序员的简单解释。 Pet类似于Pet*Pet ./P> 最终宠物类似于Pet*constpet使指针 const 但不是值本身。 爪哇和

但在下面的代码中,我可以在
pet
中赋值。i、 e.
pet.id=newobjectid(newPetId)

在Java中,关键字“final”只是表示一旦初始化,就不能更改变量的值。 比如说,

final int x = 0;`
//You can't do this!!!
int x=5

<>与变量调用方法无关。

< P>引用埃里克的评论中的回答,我找到了C++程序员的简单解释。
Pet类似于
Pet*Pet ./P>
最终宠物类似于
Pet*constpet使指针<代码> const 但不是值本身。

<>爪哇和C++有细微差别。

<>在C++中,当声明一个<代码> const 变量时,必须赋值,但在爪哇,它允许您稍后只做一次。java中的“最后”的

表示这个

1.如果在类之前使用“final”,则表示没有机会为该类创建子类

public final class Person {
void getName() {

}
}

那你就不能这样创造了

public class Man extends Person{
}
"The type Man cannot subclass the final class Person" will be shown
  • 如果在方法之前写“final”,那么

    public  class Person {
    final void getName() {      
    }   
    }
    
  • 然后可以为这个Person类创建子类,但不能重写子类中的getName()

    public class Man extends Person{
    
    @Override
    void getName() {
        // TODO Auto-generated method stub
        super.getName();
    }
    
    }
    
    "Cannot override the final method from Person" will be shown.
    
  • 如果在类中的变量之前写入“final”,则不能更改该变量的值
  • 例如:

    public  class Person {
    public final String name;
    void getName() {
    
    }   
    }
    
    然后在子类中,您不能修改该值

    public class Man extends Person{
    
    public void getName() {
        name = "child";
    }
    
    }
    "The final field Person.name cannot be assigned" will be shown
    
    所有这些都将在编译时本身中显示


    希望这对您有所帮助。

    对象的final表示对对象的引用不能更改,但并不表示对象本身不能更改。因此,
    pet
    不能重新分配给其他值,但可以更改pet的名称或其他属性。但如果你在谷歌上搜索的话,就有足够的内容来阅读了。@ErikPragt谢谢你。你的解释澄清了我的困惑。为你自己的问题发布答案感到烦恼。你不能更改“参考”-这是不同的
    public class Man extends Person{
    
    public void getName() {
        name = "child";
    }
    
    }
    "The final field Person.name cannot be assigned" will be shown