85

Is it possible to create an instance of an interface in Java?

Somewhere I have read that using inner anonymous class we can do it as shown below:

interface Test {
    public void wish();
}

class Main {
    public static void main(String[] args) {
        Test t = new Test() {
            public void wish() {
                System.out.println("output: hello how r u");
            }
        };
        t.wish();
    }
}
cmd> javac Main.java
cmd> java Main
output: hello how r u

Is it correct here?

Community
  • 1
  • 1
Ninja
  • 1,166
  • 2
  • 9
  • 16

7 Answers7

96

You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,

public interface A
{
}
public class B implements A
{
}

public static void main(String[] args)
{
    A test = new B();
    //A test = new A(); // wont compile
}

What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.

sapht
  • 2,789
  • 18
  • 16
Chad La Guardia
  • 5,088
  • 4
  • 24
  • 35
  • 13
    Anonymous classes don't have names....anonymous – jjnguy Jan 03 '11 at 19:08
  • 1
    He's asked if his example was correct, and it is. Not sure if you have acknowledged that... – rsenna Jan 03 '11 at 19:11
  • 4
    The example works...but not like he thinks it does. Its important to understand what the code is really doing. I wouldn't call it "correct" if the code is something different then he thinks it is. – Chad La Guardia Jan 03 '11 at 19:14
  • @JJnguy, all classes have names. In the case of an anonymous class it is generated by the compiler. You can perform getClass().getName() in an anonymous class and get its name. You can use this name to access it via reflection. – Peter Lawrey Jan 03 '11 at 19:17
  • @Peter, well you don't give anonymous classes names. But I suppose they do get named. – jjnguy Jan 03 '11 at 19:19
  • @claguardia: No, even after your last edit it is wrong - The anonymous class is **not** named `Test`! He is creating an object of an *anonymous* type, that *implements* the interface `Test`. I know your intentions are good, but if you want to correct someone, please do it right! – rsenna Jan 03 '11 at 19:20
  • Hmmm, yes I think Peter is right. Upon looing into this further, Local classes have a slightly different syntax in Java. What I said originally is correct. If you look at the linguistics of Java, they define the syntax for a Anonomous class like this `new class-name ( [ argument-list ] ) { class-body } `. Keyword there is class-name. – Chad La Guardia Jan 03 '11 at 19:21
  • @rsenna I think you are right. Apparently there is syntax for anonomous classes to do this, defined like this: `new interface-name () { class-body }`. However, this is simply creating a class that implements the interface, not actually constructing an instance of the interface. Good find, and I have updated my answer to reflect this. I would be curuious how to reach it with reflection though. I wonder what the compiler calls it. – Chad La Guardia Jan 03 '11 at 19:28
  • @claguardia: this would get called called something like Main$1. The Sun compiler usually uses $ followed by some digits for all sorts of synthetic constructs - i don't believe that's required by a specification anywhere, BICBW. As for whether the class has a name - in terms of the rules of the Java language, it doesn't (ie there is no name you can use as a class name in the source that will refer to the anonymous class), but in terms of the rules of the Java virtual machine, it does. It's a bit of a leaky abstraction. – Tom Anderson Jan 03 '11 at 20:43
  • Thanks Guys. Now I think Idea is clear. i.e. We can't create an instance of an interface, but here I have created an anonymous class implementing that an interface then assign this class object to the interface's reference, and is call the method through that refrence, am I right here now?? – Ninja Jan 05 '11 at 18:51
  • But at the line Test t=new Test(){} , whats the meaning of new Test() here? Is that the name of the innerClass we are creating is also kept as Test or it is used just to mention that the class implements the interface? – Ninja Jan 05 '11 at 18:53
  • 2
    If you look at one of the above comments, you'll see the syntax requires the `interface-name` so that the compiler knows the anonomous object implements the interface. Its just part of the grammar of the language. – Chad La Guardia Jan 05 '11 at 19:02
  • the code will compile by using interface by this way A test = new A() and also u can call the method of its implemented class. – Hariprasath Apr 17 '14 at 10:04
  • @ChadLaGuardia great explaination! straight to the point! – Thor Jan 08 '16 at 01:43
  • Is there ANY sense having an interface without any method declaration inside? (except for purpose of showing that interface with nothing inside cannot be instantiated) – Marian Paździoch Apr 06 '16 at 08:01
63

Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:

interface ProgrammerInterview {
    public void read();
}

class Website {
    ProgrammerInterview p = new ProgrammerInterview() {
        public void read() {
            System.out.println("interface ProgrammerInterview class implementer");
        }
    };
}

This works fine. Was taken from this page:

http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/

Community
  • 1
  • 1
Magnus
  • 646
  • 6
  • 2
  • 1
    is this compile without errors, According to my knowledge interfaces cannot be instantiated, but in you answer it is done through the line `ProgrammerInterview p = new ProgrammerInterview () {` – Kasun Siyambalapitiya Jul 24 '16 at 08:02
  • 2
    in the above example we have not instantiated an object of ProgrammerInterview but what we have done is we used ProgrammerInterview to create reference and then created an object of anonymous class. This anonymous class implemented ProgrammerInterview and created object of the anonymous class in one go. – Sargam Modak Aug 21 '16 at 06:05
  • 3
    But aren't you calling `new ProgrammerInterview () {...` ? So technically you are making an instance of the interface. I am still a little confused on what is happening here. –  Jan 24 '17 at 16:48
  • If this anonymous class `ProgrammerInterview` were created inside a `main()` method then we could access it's method `read()` by calling `p.read()`. – Ram Jun 05 '18 at 20:29
6

Normaly, you can create a reference for an interface. But you cant create an instance for interface.

Mooh
  • 1,237
  • 3
  • 19
  • 38
4

Short answer...yes. You can use an anonymous class when you initialize a variable. Take a look at this question: Anonymous vs named inner classes? - best practices?

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Liviu T.
  • 23,584
  • 10
  • 62
  • 58
  • 1
    I would say no... Because anonymous implements the interface... But you dont have implements keyword –  May 02 '16 at 14:32
3

No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.

Ketan G
  • 507
  • 1
  • 5
  • 21
0

Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc

Veerendra K
  • 2,145
  • 7
  • 32
  • 61
0

Yes it is correct. you can do it with an inner class.

zinan.yumak
  • 1,590
  • 10
  • 9
  • This seems the most correct of the answers, even though there is no explanation. For you Android programmers, Google provides an example of an class **instantiating** an inner interface [here](https://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents). – SMBiggs Aug 10 '16 at 15:06