如果我做 Object a=b 然后 b.change() 也会改变吗? [英] If I do Object a=b and then b.change() will a change as well?

查看:138
本文介绍了如果我做 Object a=b 然后 b.change() 也会改变吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有

public class Bike{
    private int speed;

    public void setSpeed(int speed){
        this.speed=speed;
    }

   public int getSpeed(){
        return speed;
    }

然后如果我创建 Bike a=new Bike();我愿意

then if I create Bike a=new Bike(); and I do

Bike b=a;
b.setSpeed(12);

自行车a的速度也会改变吗?如果没有,有没有办法做到这一点?

Will the speed of bike a change as well? If not is there any way to do that?

推荐答案

是的,它会改变.Java 赋值操作只是为对象创建一个新的引用.换句话说,写一些像

Yes it will change. The Java Assignment operation just creates a new reference to the object. In other words writing something like

Object objectA = objectB 

复制对象中的所有值.objectA 和 objectB 都指向类的同一个实例.

will not copy all values in the object. Both objectA and objectB point to the same instance of the class.

如果你想复制一个对象的所有值,你应该看看clone

If you want to copy all values of an object you should take a look at clone

这篇关于如果我做 Object a=b 然后 b.change() 也会改变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆