Home Java: Reference variable of object not updating to new instance of object?
Reply: 0

Java: Reference variable of object not updating to new instance of object?

user1814 Published in July 16, 2018, 3:06 am

I've written a small program of a car advertisement, but I'm confused as to why my variable c1 does not update to the newest car object that was made in my setter methods.

public class coolCars {
    public static void main(String args[]) {
        Car c1 = new Car("Barry", "998D", "Prius", 50, 1800.50);

And then here's my 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 + ") ";}

As mentioned above, the owner variable is not updating which means c1 is still pointing at the initial instance of the object. Any ideas? Thanks.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.323968 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO