Search code examples
javaqueuejmsmessage

Queue Connection Instantiated?


I'm doing an example of a message queue. When I look at the documentation, QueueConnection is an interface, but it's being instantiated in sample code. How is this possible? I know it extends the Connection interface. All explanations would be nice to help further my knowledge :)


Solution

  • I'm going to focus on a very specific part of your question

    QueueConnection is an interface, but it's being instantiated in sample code

    Consider the following code :

    public class Program {
        public static void main(String[] args){
            MyInterface myVar = new MyInterface(){ 
                public void myMethod(){ 
                    System.out.println("hello World"); 
                }
            };
            myVar.myMethod();
        }
    
        private interface MyInterface{
            void myMethod(); 
        }
    }
    

    Basically an interface is a contract and any class that instantiates it must fulfill the contract. If you can write an anonymous class you can make it appear as though you'e instantiated the interface.

    You can even do something like this (Although it serves no purpose)

    public class Program {
        public static void main(String[] args){
            MyInterface myVar = new MyInterface(){ };
        }
    
        private interface MyInterface{ }
    }
    

    You can see more about this here : https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html