Use of This in Java -
how increment method calling work in following code:
public class leaf { int = 0; leaf increment(){ i++; return this; } void print(){ system.out.println("i = "+ i); } public static void main(string args[]){ leaf x = new leaf(); x.increment().increment().increment().print(); } }
that example of method chaining.
by returning this
, subsequent calls instance methods of original object instance can made in chain.
each call increment()
increases value of i
1, since call acting on original object instance.
finally, print()
called on original object instance output value of i
.
Comments
Post a Comment