0

I'm going through one code, Its below. Here Runnable is an interface and implemented by Anonymous class and Interface's method is being implemented here. Upto here it sounds correct. But How this syntax is possible "new Runnable" ?

public class Library extends JFrame {
    static Library frame;
    private JPanel contentPane;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() { //Why its not giving error here ?
            public void run() {
                try {
                    frame= new Library();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

if I do like this

public interface MyInterface {

}
public class Test implements MyInterface{
    public static void main(String[] args) {
        MyInterface object  = new MyInterface(); // Error Here "Cannot instantiate the type MyInterface" Its a right Error ...!
    }

May I know please what is the difference between above two approaches ? Both are doing the same thing. Class is Implementing interface, Is there any difference ?

My Understanding say, Interface type can only reference to the objects of class which implements them. Is it correct ?

Can anyone help me to understand this ?

Squeez
  • 343
  • 2
  • 3
  • 15
  • 1
    Learn about anonymous inner classes. – SLaks Apr 12 '18 at 15:13
  • Furhtermore, interfaces can have method prototypes (i.e. methods without bodies). How would you instantiate such a thing if not through a concrete implementation (i.e. some class that implements this interface)? – Turing85 Apr 12 '18 at 15:14
  • @Turing85, I'm not asking about Implementation. My concern is HOW THIS IS POSSIBLE "new Runnable()" ? – Squeez Apr 12 '18 at 15:16
  • 1
    It is not. That is my point. You cannot instantiate interfaces. You can implement them with annonymous classes. – Turing85 Apr 12 '18 at 15:18

0 Answers0