I have the following classes in my java project Wheels, Engine, Brake which all implement CarPart
Objects created are stored in an ArrayList<CarPart> parts variable.
I want to check three things:
- Does my car have any Wheels?
- Does my car have any Engine?
- Does my car have any Brake?
I can write the hasWheels function, then write literally the same code again but replace Wheels with Engine, then with Brake. Its all duplicate code. Is there a way where I can pass a parameter to a function like doesArrayContain(parts, Wheels)?
public boolean hasWheels(ArrayList<CarPart> parts) { for (CarPart part : parts) { if (part instanceof Wheels) return false; } return true; } Something like this
public boolean doesArrayContain(ArrayList<CarPart> parts, Type type) { for (CarPart part : parts) { if (part instanceof type) return false; } return true; }
Classobject and use itsisInstancemethod.doesArrayContain(ArrayList<CarPart> parts, Class type)