Is there a similar way to declare a with-statement in Java (as in Javascript), or are there structural reasons why this would not be possible?
For example, this Javascript:
with(obj)
{
getHomeworkAverage();
getTestAverage();
getAttendance();
}
…is nice and easy. However, it would seem that method calls have to be chained to their object(s) every time in Java, with no such graceful shortcuts avaiable:
obj.getHomeworkAverage();
obj.getTestAverage();
obj.getAttendance();
This is very redundant, and especially irritating when there are many methods to call.
- So, is there any similar way to declare a with-statement in Java?
- And if this is not possible, what are the reasons that it is possible in Javascript as compared to not possible in Java?
If the class of
objis under your control, you could provide a Fluent interface, basically returningthisin every function. This would let you chain method calls like this-obj.getHomeworkAverage().getTestAverage().getAttendance();