KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
While answering a few questions on here earlier and from some work I have been doing lately I have been wondering why Java does not support method chaining on its built in classes. If I were to create a Car class for example, I could make it chainable by reutrning this instead of void as follows: public class Car { private String make; public Car setMake(String make) { this.make = make; return this; } } Is there any particular reason why the built in libraries don't tend to do things this way? Is there a downside to method chaining? I may have overlooked something which would explain the lack of method chaining however any setter method that returns void by default should return a reference to this (at least in my eyes it should). This would make situations like the following much cleaner. container.add((new JLabel("label text")).setMaximumSize(new Dimension(100,200))); rather than the more long winded: Note: It would not stop you from coding this way if you wished. JLabel label = new JLabel("label text"); label.setMaximumSize(new Dimension(100,200)); container.add(label); I would be very interested to hear the reasons behind this decision, If I had to guess it would be that there is an overhead associated with this and so should only be used when needed.
Tags (comma-separated)
Save Edits
Cancel