Reputation:
I'm currently working on a homework assignment that illustrates the basics of OOP in Java. It's a very simple carwash simulation. I have two methods in the Car
class, isDirty
and getDirty
. I have a boolean
variable Dirty
in the car class which is set to false
because all 3 cars are supposed to start out clean. I'm supposed to check all 3 cars with the isDirty
method to show that all 3 cars start out clean, after, I'm supposed to run the getDirty
method to make the cars dirty and then run the isDirty
method to show that the status changed from clean to dirty. For some reason the boolean
variable Dirty
isn't changing to true after running the getDirty
method.
public class CarwashSimulation
{
Carwash suds = new Carwash();
Car carA = new Car();
Car carB = new Car();
Car carC = new Car();
public void runSimulation()
{
System.out.println("Start Simulation");
carA.isDirty();
carB.isDirty();
carC.isDirty();
carA.getDirty();
carB.getDirty();
carC.getDirty();
carA.isDirty();
carB.isDirty();
carC.isDirty();
}
}
class Carwash
{
public void washCar()
{
}
}
class Car
{
boolean Dirty = false;
public void getDirty()
{
boolean Dirty = true;
}
public boolean isDirty()
{
if (Dirty == true)
{
System.out.println("It's Dirty");
return true;
}
else
{
System.out.println("It's Clean");
return false;
}
}
}
Upvotes: 1
Views: 177
Reputation: 20185
In method getDirty()
, a new variable boolean Dirty
is created and assigned the value true
. However, what we want is to set the (existing) field Dirty
to true
. In order to achieve this, we only need to remove the boolean
:
class Car {
...
public void getDirty() {
Dirty = true;
}
...
}
Some remarks on the code:
Dirty
-> dirty
)get
in method names is normally used for getters. I would suggest to rename getDirty()
to something like makeDirty()
so that a user does not confuse it for a getter.Upvotes: 3
Reputation: 311308
getDirty()
is not updating the data member, but declaring a local boolean that hides the data member, initializes it to true
and then discards it when it goes out of scope. Remove the declaration, and you should be OK:
public void getDirty()
{
Dirty = true; // Here!
}
Side note:
If this method is supposed to set the dirty state, setDirty
is probably a better name for it.
Upvotes: 2