Results 1 to 6 of 6
  1. #1
    logicbug's Avatar
    logicbug is offline Member
    Join Date
    Jan 2009
    Location
    The Great White North, eh?
    Posts
    76
    Rep Power
    0

    Question [SOLVED] Why interfaces

    I've never had a reason to use interfaces, but in my quest to become a more robust java developer am now taking a stronger look at them.

    To me they seem little more than extra and un-neccessary code. No matter how many classes implement an interface, you have to re-write the methods in each class. It seems to me that you can do that without an interface.

    Perhaps its just the collection of poor examples I've been able to dig up, and none of my books give an adaquit reason to use them.

    Can anyone give a real practical example of a situation where it's necessary to write an interface? No one around here can.

  2. #2
    Paul Richards is offline Member
    Join Date
    Oct 2008
    Location
    UK
    Posts
    65
    Rep Power
    0

    Default

    There are many examples in the Java API itself. I am working on a large Java application now, and I have 17 different classes that implement ActionListener. They all respond to the click of a button, but they all do different things, and therefore implement the interface in different ways.

  3. #3
    logicbug's Avatar
    logicbug is offline Member
    Join Date
    Jan 2009
    Location
    The Great White North, eh?
    Posts
    76
    Rep Power
    0

    Default

    That doesn't provide any help. In implementing the Action Listener your creating methods for what to do when the event happens, somewhere in the back ground is other code that actually does the listening.

    When you make your own interface, you arn't providing anything more than a definition and every implementation has to have its own code. So why create the definitions(interface) anyway?

    The two things, while being called the same seem to be quite different and I can't find anything that reconciles the two.

    What would really help is a small example program that uses an interface, that will cease to work if you comment out the interface and the implements.. with an explanation why it fails. Every example I've tried, works fine when you remove the interface...
    Last edited by logicbug; 01-09-2009 at 05:53 PM.

  4. #4
    Paul Richards is offline Member
    Join Date
    Oct 2008
    Location
    UK
    Posts
    65
    Rep Power
    0

    Default

    I create interfaces not out of necessity, because it is a good design decision if I find that several classes have the same specification, but different structure.

    I have found one benefit is that I can use generics/collections to store groups of objects that obey the interfaces. You can then call the interface methods on the things in your collection. This could be done without using interfaces, but it would require more coding, since you would end up with separate collections for each class.

    I have written a simple example; I'm afraid it uses a built-in interface, Shape. You could have three arrays: one for the Ellipse2D objects, one for Point2D and one for Rectangle2D. You'd then need three separate for loops for each operation, which would make the code more verbose and less intelligible.

    Java Code:
    import java.awt.Polygon;
    import java.awt.Shape;
    import java.awt.geom.Ellipse2D;
    import java.awt.geom.Point2D;
    import java.awt.geom.Rectangle2D;
    
    /**
     * Demonstrates the use of the Shape interface
     */
    public class Main {
        
        
        public static void main(String[] args) {
            //initialise an array of shapes
            Shape[] shapes = new Shape[3];
            shapes[0] = new Ellipse2D.Double(5,5,10,10);
            shapes[1] = new Rectangle2D.Double(-5,-5,10,10);
            int[] xpoints = {0,1,3,2,0,-1,-2,0};
            int[] ypoints = {4,5,0,-2,-1,-1,4,4};
            shapes[2] = new Polygon(xpoints, ypoints, xpoints.length);
            
            //count how many shapes contain the point (0,0)
            Point2D.Double origin = new Point2D.Double(0,0);
            int total = 0;
            for(Shape s: shapes) {
                if(s.contains(origin)) {
                    total++;
                }
            }
            System.out.println("Number of shapes containing the origin: "+total);
            
            //find the smallest rectangle that encloses all the shapes
            Rectangle2D allbounds = null;
            for(Shape s: shapes) {
                Rectangle2D bounds = s.getBounds();
                allbounds = (allbounds==null) ? bounds : allbounds.createUnion(bounds);
            }
            System.out.println("Bounds of all the shapes: "+allbounds);
        }
    }

  5. #5
    racerxadam is offline Member
    Join Date
    Jul 2008
    Posts
    68
    Rep Power
    0

    Default

    Off the top of my head a concrete example would be something like the java.sql.Connection Interface. If I do something like below, as long as the MyDriver class implements the Connection Interface, the variable "myConnection" can use all the methods in the Connection API without worrying about how they work.

    Java Code:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    
    public class TestConnection {
    
    	public Connection getConnection() {
    
    		Connection myConnection = null;
    		try {
    			Class.forName( "org.domain.MyDriver" );
    			myConnection = DriverManager.getConnection( "someURL", "userName", "PassWord" );
    			return myConnection;
    		}
    		catch ( ClassNotFoundException e ) {
    			e.printStackTrace();
    		}
    		catch ( SQLException e ) {
    			e.printStackTrace();
    		}
    		finally {
    			try {
    				myConnection.close();
    			}
    			catch ( SQLException e ) {
    				e.printStackTrace();
    			}
    		}
    		return null;
    	}
    }

  6. #6
    neilcoffey is offline Senior Member
    Join Date
    Nov 2008
    Posts
    286
    Rep Power
    6

    Default

    Interfaces allow you to specify "what's common" about some classes that otherwise wouldn't necessarily have a common superclass that implemented those common methods.

    Consider Comparable, for example. Instead of defining it as an interface, the JDK could instead have defined it as an abstract class. And so to implement a Comparable object, you would then have had to subclass that abstract class. That's fine if you don't need to subclass anything else, but otherwise you're a bit stuck. By making Comparable an interface instead, it means that "any old class" can have the features of Comparable tacked on to it without otherwise affecting which class(es) it inherits from.

    Another example is CharSequence. This is implemented by various things that "hold characters"-- such as String, CharBuffer, StringBuilder etc-- but which otherwise don't really have a common ancestor. By adding the interface, is is possible to write very generic methods that can operate on "any old object that contains characters"-- otherwise, you'd have had to pick a specific class or specific subclass and, as I say, there is no subclass that you could pick to work with all of these objects. Now, imagine that you want to make your own character-holding class (for example, I have suggested a "CompactCharSequence" class to reduce String memory usage). If I had to extend one of the JDK classes to make it work with other character sequence manipulation methods, what would I extend? By only having to implement an interface, I'm free for my object to inherit from whatever it wants, it will still work with any method that takes a CharSequence (e.g. regular expression matching).
    Last edited by neilcoffey; 01-09-2009 at 08:48 PM.

Similar Threads

  1. Interfaces
    By jon80 in forum New To Java
    Replies: 2
    Last Post: 05-03-2008, 09:57 PM
  2. interfaces..
    By sireesha in forum New To Java
    Replies: 5
    Last Post: 01-16-2008, 05:52 PM
  3. Interfaces
    By Kavana Krishnappa in forum New To Java
    Replies: 7
    Last Post: 12-11-2007, 04:28 PM
  4. Interfaces
    By imran_khan in forum New To Java
    Replies: 5
    Last Post: 07-30-2007, 08:11 AM

Posting Permissions

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