Results 1 to 6 of 6
  1. #1
    frejon26 is offline Member
    Join Date
    Jan 2008
    Posts
    14
    Rep Power
    0

    Default interface purpose?

    obviously interfaces have some kind of purpose but it is lost on me... I have searched high and low for an answer to this question and maybe someone here can help.
    -So interfaces are java's way of implementing behavior when multiple inheritance is not tolerated, and it is also a sort of "contract" that a program binds with the interface, (if an interface declares a certain amount of methods, and a class implements the interface, the class must also implement all of the methods declared in the interface.)
    Here is my question...
    if all that an interface provides is "empty" method declarations (and some constants maybe), how does this add any functionality to a class? you still have to write the methods youself when you implement the interface, why couldn't you just write the methods yourself and not implement the interface? or for instance there is an interface "Serializable" for storing a class as an object for retrieval later, but what would this interface declaration look like?

    public interface Serializable{
    }

    how would this add any functionality, or object "behavior"? it seems to me that there is a lot happening in the background other than just empty method declarations.
    thanks ahead to anyone who can shed some light on these questions I've been having. :)

  2. #2
    frejon26 is offline Member
    Join Date
    Jan 2008
    Posts
    14
    Rep Power
    0

    Default

    sorry for the long question before, I guess it can be summed up better.

    Are programmer defined interfaces different from predefined "Java" interfaces?
    Do the Java interfaces supply more functionality while programmer defined interfaces are... maybe only for contract sake?

    again sorry I just have been trying to figure this out for a long time and I have been looking around alot.

  3. #3
    XiaoXiao is offline Member
    Join Date
    Jan 2008
    Posts
    6
    Rep Power
    0

    Default Interfaces are just contracts

    hi frejon26,
    Are programmer defined interfaces different from predefined "Java" interfaces?
    Do the Java interfaces supply more functionality while programmer defined interfaces are... maybe only for contract sake?
    There is absolute no difference between programmer defined interfaces and java interfaces.
    No, java interfaces dont supply any functionality other than method declarations and some constants.

  4. #4
    tim's Avatar
    tim
    tim is offline Senior Member
    Join Date
    Dec 2007
    Posts
    435
    Rep Power
    7

    Default

    Hello frejon26

    Quote Originally Posted by frejon26
    Java Code:
    public interface Serializable{
    }
    how would this add any functionality, or object "behavior"?
    Some interfaces are like tags. If you create a class that can be serialized, that is sent through a stream, then it must be "tagged" as Serializable. To do that, we let our new class implement the Serializable interface. Well, thats how I understand it.

    Hope that helped. ;)
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

  5. #5
    gibsonrocker800's Avatar
    gibsonrocker800 is offline Senior Member
    Join Date
    Nov 2007
    Location
    New York
    Posts
    143
    Rep Power
    0

    Default

    i once had the same question. My teacher answered it by saying that interfaces are a way of organizing similar classes. So, technically they serve no functionality to a class. Although it can be useful. Say we have a class that calls for a Comparable

    Java Code:
    public Example(Comparable c)
    {
        //code
    }
    As you can see, sometimes constructors or methods may call for an object that implements a certain interface. So if we wanted to use this example class with another class, we must make the other class implement Comparable, and of course defining compareTo(). This is a common thing because sometimes classes need to make sure that the objects can be compared. I'll give you a perfect example. The class TreeSet.

    "but a TreeSet instance performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the set, equal."

    This shows how TreeSets must be used on objects that can be compared because TreeSets sort the elements according to their compareTo definition. So, let's say that we have a class called BankAccount, that implements Comparable, so we must define compareTo().

    Java Code:
    public class BankAccountA implements Comparable
    {
         private int balance;
         public BankAccountA(int initialBalance)
         {
              balance = initialBalance;
         }
    
         public int getBalance()
         {
               return balance;
         }
    
         public int compareTo(Object bank)
         {
        	  BankAccountA b = (BankAccountA)bank; //We must cast the parameter as a BankAccountA
              if(balance == b.getBalance())
                    return 0; //They are equal
              else if(balance < b.getBalance())
                    return -1; //The balance is less than the other balance
              else
                    return 1;   //The balance is greater than the other balance
         }
         
         public String toString()
         {
        	 return "Balance = " + balance;
         }
    }
    In this case, the accounts are compared according to their balance. Now, let's make another BankAccount class that compares accounts by account number.

    Java Code:
    public class BankAccountB implements Comparable
    {
         private int account;
         public BankAccountB(int accountNumber)
         {
              account = accountNumber;
         }
    
         public int getAccountNumber()
         {
               return account;
         }
         public int compareTo(Object bank)
         {
        	 BankAccountB b = (BankAccountB) bank; //We must cast the parameter as a BankAccountB
              if(account == b.getAccountNumber())
                    return 0; //They are equal
              else if(account < b.getAccountNumber())
                    return -1; //The number is less than the other numer
              else
                    return 1;   //The number is greater than the other number
         }
         
         public String toString()
         {
        	 return "AccountNumber = " + account;
         }
    }
    So now we will make a tester class to demonstrate how this will work. I'm going to use TreeSet. Ignore the iterator, just know that it allows you to retrieve the objects in the set.

    Java Code:
    import java.util.*;
    public class BankAccountTest {
    
    	public static void main(String[] args) 
    	{
    		Set<BankAccountA> aSet = new TreeSet<BankAccountA>();
    		aSet.add(new BankAccountA(50));
    		aSet.add(new BankAccountA(25));
    		aSet.add(new BankAccountA(100));
    		
    		Iterator<BankAccountA> iter = aSet.iterator();
    		
    		System.out.println("BankAccountA Info: ");
    		while(iter.hasNext())
    		{
    			//Since System.out.println() calls toString() on its parameters
    			//which we defined in the class, we can have put the object in println(), 
    			//if we didn't define toString(), this statement would print the memory location
    			//of the object because that is the default purpose of toString()
    			System.out.println(iter.next()); 
    		}
    		
    		/*
    		 * This shows the way it works for BankAccountB
    		 */
    		
    		Set<BankAccountB> bSet = new TreeSet<BankAccountB>();
    		bSet.add(new BankAccountB(2000));
    		bSet.add(new BankAccountB(1000));
    		bSet.add(new BankAccountB(4000));
    		
    		Iterator<BankAccountB> iter2 = bSet.iterator();
    		System.out.println("-------------------");
    		System.out.println("BankAccountB Info: ");
    		while(iter2.hasNext())
    		{
    			System.out.println(iter2.next()); 
    		}
    		
    
    	}
    
    }

    As you will see, the program outputs:

    Balance = 25
    Balance = 50
    Balance = 100
    -------------------
    BankAccountB Info:
    AccountNumber = 1000
    AccountNumber = 2000
    AccountNumber = 4000

    Now, if we were to make it so that BankAccountA and B do NOT implement Comparable, here is the error we would get
    in the tester:
    Exception in thread "main" java.lang.ClassCastException: BankAccountA cannot be cast to java.lang.Comparable
    at java.util.TreeMap.put(Unknown Source)
    at java.util.TreeSet.add(Unknown Source)
    at BankAccountTest.main(BankAccountTest.java:8)

    This indicates the use of interfaces: some classes can call for objects that implement a certain interface, in the case of TreeSet,
    the object must be a Comparable. I know this is extremely long, but I think it will help you understand. Hope this helps man!

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,086
    Rep Power
    20

    Default Re: interface purpose?

    OK, this is ridiculous.
    You're opening ancient threads to post links to what I can only presume is your website.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. DERS Interface
    By Floetic in forum AWT / Swing
    Replies: 2
    Last Post: 03-09-2008, 10:46 PM
  2. Need help with Document interface
    By cbalu in forum AWT / Swing
    Replies: 1
    Last Post: 11-30-2007, 11:03 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
  •