Results 1 to 2 of 2
  1. #1
    bugger is offline Senior Member
    Join Date
    Nov 2007
    Posts
    111
    Rep Power
    0

    Default Implementing an interface

    Hello!

    I am defining an interface.

    Java Code:
    interface Parser{
    
           void parseText(String buffer);
           void parseInt(String buffer);
           void parseFloat(String buffer);
    
    }
    Now the classes implementing this interface have to implement these methods. I want to keep the implementation of parseText(...) method as optional. The class implementing this interface have to implement parseInt(...) and parseFloat(...) but parseText(...) should be optional.

    How this can be done?

    Thanks a lot for yout time.
    - Cheers

  2. #2
    jelly's Avatar
    jelly is offline Member
    Join Date
    Jan 2008
    Location
    Somerset, UK
    Posts
    46
    Rep Power
    0

    Default

    An interface is best thought of as a contract, if you implement the interface then you need to implement the methods. You _ could_ simply implement parseText as

    parseText(...) {}

    but that would confuse the calling code that would have expected some process to have taken place. If you do not want all classes to implement parseText then perhaps two interfaces

    interface Parser{

    void parseInt(String buffer);
    void parseFloat(String buffer);

    }

    interface SuperParser extends Parser {
    void parseText(String buffer);
    }

    The second interface is now a subinterface of the first and adds additional capability. A user could check what capabililty is available via the instanceOf keyword

    if ( someObjRef instanceOf SuperParser) {
    someObjRef.parseText(...);
    }
    -- Hope that helps

Similar Threads

  1. Implementing Interface
    By mew in forum New To Java
    Replies: 4
    Last Post: 02-16-2010, 03:33 PM
  2. Implementing Serializable interface
    By javaplus in forum Advanced Java
    Replies: 4
    Last Post: 12-18-2007, 12:29 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •