Results 1 to 6 of 6
  1. #1
    makpandian's Avatar
    makpandian is offline Senior Member
    Join Date
    Dec 2008
    Location
    Chennai
    Posts
    450
    Rep Power
    7

    Default Advantage of Using Interface Over Class.

    Hello,
    I think this thread may be stupid one.But as for me it s more important to enhance java Basics.

    We can do all application with the help of class only but not interface.Then why we have been using interface for long time in out java application?

    all of us should share one reason about this thread.

    Thanks a lot.
    Mak
    (Living @ Virtual World)

  2. #2
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    With an interface you can force classes that implement the interface to implement (add) the methods that are in that interface. This is also possible with an abstract class, but:
    1) You need to extend the abstract class. Because you only can extend one class you cannot extend another class. Example: applets, where you have to extend the Applet class.
    2) Certain things you can do using an interface you can't do using an abstract class.

    Example:
    Java Code:
    public class TestClass implements TestInterface          
    {
        public static void main(String[] args) {
            new TestClass();
        }
    
        public TestClass() {
            TestButton b = new TestButton();
            b.addTestActionListener(this);
        }
    
        public void actionPerformed() {
            // This method is implemented with TestInterface
        }
    }
    
    
    public interface TestInterface 
    {
        public void ActionPerformed(); // User has to implement this method
    }
    
    
    public class TestButton
    {
    
        TestInterface ti;
    
        public TestButton() {
            // Construct new
        }
    
        public void addTestActionListener(TestInteraface ti) {
            this.ti = ti;
        }
    
        public void blabla() { // Assume this method is called when the button is pressed.
    
            // You want this action to be 'passed' to the component on which the button is placed, so you use:
            ti.actionPerformed();
      
        }
    }
    This, for example, you can't do with an abstract class.

    ~Matt
    I die a little on the inside...
    Every time I get shot.

  3. #3
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    @SupaMagier: If you wanted to you could actually use an abstract class in place of the interface, simply because nothing extends anything. One bonus of interfaces is multiple inheritance(of a kind)... a class can be an ActionListener, MouseListener, WindowListener, and also extend a JFrame.

    Heres a good one. It has muliple implementation of interfaces (IMPORTANT) and most of the classes extend something. Compiles too :D

    Java Code:
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.event.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import javax.swing.*;
    
    public class WhyAnInterface {
    	private SimpleDateFormat dFormat = new SimpleDateFormat("h:mm:ss a");
    	public interface MessageListener{
    		void printMessage(Message m);
    		void receiveMessage(Message m);
    	}
    	public static class Message{
    		
    		public Date timeStamp;
    		public static Date lastMessage;
    		public String message;
    		public Message(String message){
    			timeStamp = new Date();
    			lastMessage = timeStamp;
    			this.message = message;
    		}
    	}
    	public class WAIFrame extends JFrame implements ActionListener, MessageListener{
    		private static final long serialVersionUID = 1L;
    		
    		private ArrayList<Message> cache = new ArrayList<Message>();
    		private ArrayList<MessageListener> listens = new ArrayList<MessageListener>();
    		@Override
    		public void printMessage(Message m) {
    			while(cache.size()>0){
    				outMessage(cache.get(0));
    				cache.remove(0);
    			}
    			outMessage(m);
    		}
    
    		@Override
    		public void receiveMessage(Message m) {
    			cache.add(m);
    		}
    		private void outMessage(Message m){
    			System.out.println("@ " + dFormat.format(m.timeStamp) + " someone said " + m.message);
    		}
    		JButton print = new JButton("Print"),
    		store = new JButton("Store");
    		JTextField message = new JTextField(50);
    		public WAIFrame(){
    			message.setPreferredSize(new Dimension(100, 20));
    			JPanel pane = new JPanel();
    			pane.add(message);
    			pane.add(print);
    			pane.add(store);
    			setContentPane(pane);
    			pack();
    			addMessageListener(this);
    			print.addActionListener(this);
    			store.addActionListener(this);
    			Point loc = getJFrameCenteringPoint(this);
    			loc.y = 20;
    			setLocation(loc);
    		}
    
    		public void addMessageListener(MessageListener m){
    			listens.add(m);
    		}
    		private void notifyListeners(Message m, boolean print){
    			if(print){
    				for(MessageListener ml : listens.toArray(new MessageListener[0])){
    					ml.printMessage(m);
    				}
    			}
    			else 
    				for(MessageListener ml : listens.toArray(new MessageListener[0])){
    					ml.receiveMessage(m);
    				}
    		}
    		@Override
    		public void actionPerformed(ActionEvent e) {
    			if(e.getSource() == print){
    				notifyListeners(new Message(message.getText()), true);
    				message.setText("");
    			}
    			else if(e.getSource() == store){
    				notifyListeners(new Message(message.getText()), false);
    				message.setText("");
    			}
    		}
    		
    	}
    	public class AnotherListener extends JFrame implements ActionListener, MessageListener{
    
    		private static final long serialVersionUID = 1L;
    		private ArrayList<JFrame> mFrame = new ArrayList<JFrame>();
    		private boolean nonStoreDisplayed = false;
    		public AnotherListener(){
    			JButton b = new JButton("<html>Close all <p>Message Frames</html>");
    			JPanel p = new JPanel();
    			p.add(b);
    			setContentPane(p);
    			b.addActionListener(this);
    			pack();
    			setLocation(getJFrameCenteringPoint(this));
    		}
    		
    		@Override
    		public void actionPerformed(ActionEvent e) {
    			while(mFrame.size()>0){
    				mFrame.get(0).setVisible(false);
    				mFrame.remove(0);
    			}
    		}
    
    		@Override
    		public void printMessage(Message m) {
    			generateAndDisplayMessageFrame(m);
    		}
    
    		@Override
    		public void receiveMessage(Message m) {
    			if(!nonStoreDisplayed){
    				nonStoreDisplayed = true;
    				JLabel l = new JLabel("The frames don't handle messages...");
    				final JFrame f = new JFrame();
    				JPanel p = new JPanel();
    				p.add(l);
    				f.setContentPane(p);
    				f.pack();
    				Point loc = getJFrameCenteringPoint(f);
    				loc.y -= f.getHeight()-20;
    				f.setLocation(loc);
    				new Thread(){
    
    					@Override
    					public void run() {
    						f.setVisible(true);
    						try {
    							sleep(5000);
    						} catch (InterruptedException e) {
    							f.setVisible(false);
    						}
    						f.setVisible(false);
    					}
    					
    				}.start();
    			}
    		}
    		private void generateAndDisplayMessageFrame(Message m){
    			JLabel l = new JLabel("@ " + dFormat.format(m.timeStamp) + " someone said " + m.message);
    			JFrame f = new JFrame();
    			JPanel p = new JPanel();
    			p.add(l);
    			f.setContentPane(p);
    			f.pack();
    			Point loc = getJFrameCenteringPoint(f);
    			loc.y -= f.getHeight()-20;
    			f.setLocation(loc);
    			f.setVisible(true);
    			mFrame.add(f);
    		}
    	}
    	public WhyAnInterface(){
    		AnotherListener opml = new AnotherListener();
    		WAIFrame waif = new WAIFrame();
    		waif.addMessageListener(opml);
    		waif.setVisible(true);
    		waif.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		opml.setVisible(true);
    	}
    	public static Point getJFrameCenteringPoint(JFrame f){
    		Dimension screen = f.getToolkit().getScreenSize();
    		Dimension frame = f.getSize();
    		return new Point(screen.width/2-frame.width/2, screen.height/2-frame.height/2);
    	}
    	public static void main(String[]args){
    		new WhyAnInterface();
    	}
    }
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  4. #4
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    Yea, I know, but it's quite odd if you do it that way.
    Plus, using interfaces keeps your code readable.
    I die a little on the inside...
    Every time I get shot.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Get a good book on "Design Patterns" such as the "Gang of Four's" book or the Head First book, and have a read. It will open a whole new world for you, one that illuminates the beauty of interfaces.

    Much luck.

  6. #6
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    Programming in a team. Someone else is going to implement data handling code. As long as we both use the same interface, we can both write code separately and it will work together.

    Mine:
    Java Code:
    public interface DataSource {
        public byte[] getData();
        public void setLvel(int level);
    }
    
    public class Main {
        private DataSource ds;
        public Main(DataSource ds) {
            this.ds = ds;
        }
        public void compute(int level) {
            ds.setLevel(level);
            byte[] data = ds.getData();
            // etc...
        }
    }
    Theirs:
    Java Code:
    public interface DataSource {
        public byte[] getData();
        public void setLvel(int level);
    }
    
    class Impl implements DataSource {
        private List<String> list;
        public void setLevel(int level) {
            list = new ArrayBlockingQueue(level);
        }
        public byte[] getData() {
            // etc..
        }
    }
    
    public void Init {
        public static void main(String args) {
            Main = new Main(new Impl());
            // etc.
        }
    }
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

Similar Threads

  1. What is advantage of interface in java?Plz help
    By Eyeinstyin in forum New To Java
    Replies: 13
    Last Post: 09-08-2011, 02:12 AM
  2. Replies: 14
    Last Post: 05-28-2009, 06:44 AM
  3. Interface variable to class
    By zill in forum Advanced Java
    Replies: 6
    Last Post: 10-11-2008, 04:29 AM
  4. Replies: 7
    Last Post: 09-16-2008, 07:20 PM
  5. Replies: 0
    Last Post: 04-02-2008, 08:04 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
  •