Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Interface, instantiating an interface?

So I just found this code example online a while ago and I'm going over it again but quite confused.

From looking at it, what I gather (and it might be wrong) is that it passes to the print method in the NumberPrinter class a Printer object. However, the interface is also called Printer, so aren't we instantiating an anonymous class of the Printer interface, defining the methods and then passing it?

My basic question is, is my initial assumption correct? And if so I thought you could not instantiate an interface?

public class NumberPrinter {

    public interface Printer {
        public void print (int idx);
    }

    public static void print (Printer p) {
        for (int i = 0; i < 4; i++) {
            p.print(i);
        }
    }

    public static void main(String[] args) {
        print(new Printer() {

            @Override
            public void print(int idx) {
                System.out.println(idx);
            }

        });
    }

}
like image 353
mino Avatar asked Apr 18 '12 00:04

mino


3 Answers

This is called an anonymous inner class.

It creates an un-named class that implements the Printer interface.

like image 99
SLaks Avatar answered Sep 28 '22 13:09

SLaks


Your assumption is correct, and you cannot instantiate an interface. You can instantiate an anonymous class however, which is what the code is doing.

like image 32
Jim Barrows Avatar answered Sep 28 '22 11:09

Jim Barrows


You need a Printer object for the print function of NumberPrinter. When you call that function you don't actually instantiate the Printer interface but you instantiate an implementation of it and this is why it's working.

Your assumption was correct by the way.

like image 26
Chris911 Avatar answered Sep 28 '22 12:09

Chris911