Java:对象的引用变量没有更新到对象的新实例?

时间:2017-11-12 16:43:38

标签: java class oop variables object

我写了一个汽车广告的小程序,但我很困惑为什么我的变量c1没有更新到我的setter方法中制作的最新汽车对象。

public class coolCars {
    public static void main(String args[]) {
        Car c1 = new Car("Barry", "998D", "Prius", 50, 1800.50);
        System.out.print(c1);
        c1.setOwner("Jerry");
        System.out.println(c1.owner());
        /*c1.setOwner("Mick");
        System.out.print(c1);
        c1.setKil(70);
        System.out.print(c1);*/
    }
}

然后这是我的Car class

final class Car {
    private final String owner;
    private final String reg;
    private final String make;
    private final int kilometres;
    private final double price;
    public Car(String ow, String r, String m, int k, double p) {
        owner = ow; reg = r; make = m; kilometres = k; price = p; 
    }
    public String owner(){return this.owner;}
    public String reg(){return this.reg;}
    public String make(){return this.make;}
    public int kilometres(){return this.kilometres;}
    public double price(){return this.price;}
    public Car setPrice(double p){return new Car(owner(), reg(), make(), kilometres(), p);}
    public Car setOwner(String ow){return new Car(ow, reg(), make(), kilometres(), price());}
    public Car setKil(int k){return new Car(owner(), reg(), make(), k, price());}
    public Car setMake(String m){return new Car(owner(), reg(), m, kilometres(), price());}

    public String toString(){return "(" + owner + " " + reg + " " + make + " " + kilometres + " " + price + ") ";}
}

如上所述,owner变量没有更新,这意味着c1仍然指向对象的初始实例。有任何想法吗?感谢。

3 个答案:

答案 0 :(得分:1)

您没有在所有这些方法中设置值:

public Car setPrice(double p){return new Car(owner(), reg(), make(), kilometres(), p);}
public Car setOwner(String ow){return new Car(ow, reg(), make(), kilometres(), price());}
public Car setKil(int k){return new Car(owner(), reg(), make(), k, price());}
public Car setMake(String m){return new Car(owner(), reg(), m, kilometres(), price());}

您只是返回无效的Car新实例。

这样做:

public Car setPrice(double price){ this.price = price }
public Car setOwner(String owner){ this.owner = owner }
public Car setKil(int kilometres){ this.kilometres = kilometres}
public Car setMake(String make){ this.make = make }

答案 1 :(得分:0)

setOwner方法正在创建Car的新实例。在您的main方法中,C1仍然指向最初创建的汽车对象。你需要c1 = c1.setOwner。然而,这似乎违反直觉。你的setter方法应该简单地为该对象更新Car的类级变量。不要创造一个全新的对象。

答案 2 :(得分:0)

每个Setter方法(对于price,owner,km和make)都在创建一个新的Car对象并返回它。

在以下声明中,没有作业:

c1.setOwner("Jerry");

因此,返回的Car对象(新创建的)会丢失。

通过分配修改然后尝试:

c1 = c1.setOwner("Jerry");

或者可以按照上面的建议更正Setter方法。