0

Good evening,

New to programming Java and still trying to get the hang of objects. I'm able to successfully modify the default parameters of an object when I create it. However when I create a second object and modify its parameters, it also impacts the first object and sets its parameters to the same values.

Please help when you have a chance.


public class Car {

    private static int wheels;
    private static String colour;
    private static boolean electric;
    
    public Car () {
        this.wheels = 4;
        this.colour = "default";
        this.electric = true;
    }
    
    public void setWheels(int wheels) {
        this.wheels = wheels;
    }
    
    public int getWheels() {
        return wheels;
    }
    
    public void setColour(String colour) {
        this.colour = colour;
    }
    
    public String getColour() {
        return colour;
    }
    
    public void setElectric(boolean electric) {
        this.electric = electric;
    }
    
    public boolean getElectric() {
        return electric;
    }
    
    public String toString() {
        System.out.println("Wheels: " + wheels + " Colour: " + colour + " Electric? " + electric);
        return " ";
    }
    
}

Second class which contains the main method is as follows:

import java.util.Scanner;

public class CarTesting {

    public static void main(String[] args) {

        Scanner userInput = new Scanner(System.in);
        System.out.println("Number of wheels");
        int numWheel = userInput.nextInt();
        System.out.println("Colour");
        String colour = userInput.next();
        System.out.println("Electric?");
        boolean electric = userInput.nextBoolean();
        
        Car car1 = new Car();
        Car car2 = new Car();
        
        Car autoShop[] = new Car[2];
        autoShop[0] = car1;
        autoShop[1] = car2;
        
        car1.setColour(colour);
        car1.setElectric(electric);
        car1.setWheels(numWheel);
        System.out.println(car1);
            
        System.out.println("Number of wheels");
        numWheel = userInput.nextInt();
        System.out.println("Colour");
        colour = userInput.next();
        System.out.println("Electric?");
        electric = userInput.nextBoolean();
        
        car2.setColour(colour);
        car2.setElectric(electric);
        car2.setWheels(numWheel);       
        
        System.out.println("Moment of truth");
        System.out.println(autoShop[0]);
        System.out.println(autoShop[1]);
    }

}
Steven
  • 23
  • 2

0 Answers0