I`m trying to use sets and gets for a code, but it`s not compiling
I`m not sure how to set and get a String,
this is what I have so far
this is class Car

String color;
void setColor(String col)
                 
         {
              color = col;
	}   	
		
	String getColor()
	{
	   return color;
	}

This compiles, but when I call it in my testCar class I get an error
This is class testCar

Car myCar = new Car();
myCar.setColor = "Red";

I`m having an error in my class testCar, when setting the color
Thanks guys

Recommended Answers

All 2 Replies

Not sure about your whole classes so here are some examples
Class Car

public class Car{
	//default constructor
	public Car(){}
	
        //constructor takes car colour as initialization value
	public Car(String col){
		setColor(col);
	}
	
	String color;
	public void setColor(String col)
    {
    	color = col;
	}   	
		
	public String getColor()
	{
	   return color;
	}
}

Class CarTest

public class CarTest{
	public static void main(String[] args){
		Car myCar = new Car();
		myCar.setColor("Red");
		System.out.println(myCar.getColor());
		myCar = new Car("Blue");
		System.out.println(myCar.getColor());
	}
}

I guess you misunderstood the way setters are used. The value to which you wish to assigned is passed in between brackets and not by direct assignment as you tried.
Also the value you wish to assign can be also passed directly through class declaration with use of constructor ( public Car(String col) ). Class can have number of constructors depending on your needs ( public Car(String color, String manufacturer, String fuel, int speed, boolean inStock )

PS: In the scenario when constructors are used setter methods to which parameters are passed by constructor become private. Reason is simple you do not want that any class accessing Car class can change these values randomly and possibly create havoc with your results

thanks, it compiles and runs now, the problem was what you said.
Instead of the parethesis I was setting it with the equal sign.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.