File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Doubt on interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Doubt on interface" Watch "Doubt on interface" New topic
Author

Doubt on interface

Martin Arun Paul Perumala
Greenhorn

Joined: Dec 10, 2008
Posts: 14
The following code is simple trying to take 2 variables and adding, substracting and multiplying them using interface concept.

In the demo class I want to use "function chaining" like a1.setdata().add().sub().mul(). Is it possible? I tried to do it but I guess we have to create another class. please help me

Thank you








[edit]Add code tags. CR[/edit]
[ December 13, 2008: Message edited by: Campbell Ritchie ]
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 39549
    
  27
If you want to chain methods, then they can't be "void" - in other words, return nothing. They should return the result of the previous calculation - what in the code is stored in "z".

There's no point really in using an interface here. You could use one if all the individual operations (plus, minus, multiply, ...) each had their own class; but that would be a contrived use.
[ December 13, 2008: Message edited by: Ulf Dittmer ]

Ping & DNS - updated with new look and Ping home screen widget
Martin Arun Paul Perumala
Greenhorn

Joined: Dec 10, 2008
Posts: 14
so can we change the return type (void) of the methods in the interface class to something else like object type.?
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19544
    
  16

Take a look at java.lang.StringBuilder. After modifying its contents, it returns "this":

Of course you can do the same if you want to keep your contents fixed. In that case, take a look at java.math.BigInteger. A few examples:

Both can now be chained:

The first line creates one single StringBuilder object that has three strings appended to it.
The second line creates 5 BigInteger objects:
- new BigInteger("5")
- new BigInteger("6")
- the result of 5 + 6
- new BigInteger("7")
- the result of (5 + 6) * 7

In the end, "big" will contain a value of 77.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt on interface
 
Similar Threads
read int inputs
explain this ...please
Inheritence
How to find Object type.
local variable not assigned any value in a method yet how does it compile??