I've written some code to try to better explain what it is I'm trying to achieve.
public interface Car extends ViewCar {
static Car getInstance(String make, String model){
NewCar newCar = new ConcreteCar();
newCar.setMake(make);
newCar.setModel(model);
return newCar;
}
void drive();
}
ViewCar
has showMake()
, showModel()
and showCar()
methods.
ConcreteCar
implements all methods from NewCar
. NewCar
extends Car
.
So basically as it stands
Car car = Car.getInstance("Make", "Model")
Will return a nice shiny new car.
I've got a list within a class called Cars which contains the Car object.
So as it stands, if get the list and do forEach through each car, I can drive it or show the make/model.
What I'd like to be able to do is forEach through the list using ViewCar
, which will only be able to show make/model and not drive.
Is there a better way than the code below to achieve this?
public void ViewCarCanOnlyPrintCar(){ //This works but looks a little longwinded to me
List<ViewCar> viewCars = new ArrayList(cars.getCars());
viewCars.forEach(car -> {
car.showMake();
car.showModel();
});
}
Now if I can do this...
cars.getCars().forEach(ViewCar::showCar);
Why can' I do something like this...
cars.getCars().forEach(ViewCar -> {
showMake();
showModel();
});
In my project I have an main Interface for an object which extends multiple other interfaces. I'd like to be able to pass the object around, but only allow access to certain methods.
Am I missing something glaringly obvious?
EDIT: I wan't to be able to store a list of Cars
, but then have other classes get that list of cars and only have reduced privileges. So the class that displays the car will only know how to display the make and model, not know how to drive. I understand that List<Car>
isn't a List<ViewCar>
even though I can do the following:
Car car = new Car();
ViewCar viewCar = car;
So how can I achieve a similar result? Is there a design pattern for this kind of thing? Or do I need to just pass the List<Car>
and then do
cars.forEach((ViewCar viewCar) -> {
viewCar.showMake()
})