Results 1 to 6 of 6
- 06-08-2009, 08:34 AM #1
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)
- 06-08-2009, 09:50 AM #2
Senior Member
- Join Date
- Aug 2008
- Posts
- 384
- Rep Power
- 5
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:
This, for example, you can't do with an abstract class.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(); } }
~MattI die a little on the inside...
Every time I get shot.
- 06-08-2009, 11:05 AM #3
Senior Member
- Join Date
- Mar 2009
- Posts
- 552
- Rep Power
- 5
@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!
- 06-08-2009, 11:38 AM #4
Senior Member
- Join Date
- Aug 2008
- Posts
- 384
- Rep Power
- 5
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.
-
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.
- 06-08-2009, 11:58 AM #6
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:
Theirs: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... } }
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
-
What is advantage of interface in java?Plz help
By Eyeinstyin in forum New To JavaReplies: 13Last Post: 09-08-2011, 01:12 AM -
E:\IT 215 Java Programming\public class Inventory.java:39: class, interface, or enum
By tlouvierre in forum New To JavaReplies: 14Last Post: 05-28-2009, 05:44 AM -
Interface variable to class
By zill in forum Advanced JavaReplies: 6Last Post: 10-11-2008, 03:29 AM -
Is there any real advantage of using only one listener
By playwin2 in forum New To JavaReplies: 7Last Post: 09-16-2008, 06:20 PM -
what is the Priority for execution of Interface class and a Abstract class
By Santoshbk in forum Advanced JavaReplies: 0Last Post: 04-02-2008, 07:04 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks