I would like to do a method chain, for example like this:
Car myCar = new Car();
// Chaining
myCar.config.engine.cylinders("4");
But how do I do the chaining, without using parentheses in "config" or "engine"?
I can only figure out to do it like this:
myCar.config().engine().cylinders("4");
You can do this by declaring
Config
property in yourCar
class. ThenEngine
property inCarConfig
class, like this:Then you can chain the calls.
You could use properties as many suggest, but this whole thing stinks of breaking the Law of Demeter (or Principle of Least Knowledge). Basically you are breaking the encapsulation of the Car class. You may want to take a look at Builder Pattern, especially the fluent implementations (like here).
Your code may then look like