Can we create an instance of an interface in Java?

213,953

Solution 1

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/

Solution 2

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.

Solution 3

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

Solution 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?

Solution 5

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.

Share:
213,953

Related videos on Youtube

Ninja
Author by

Ninja

Updated on July 05, 2022

Comments

  • Ninja
    Ninja almost 2 years

    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?

  • jjnguy
    jjnguy over 13 years
    Anonymous classes don't have names....anonymous
  • rsenna
    rsenna over 13 years
    He's asked if his example was correct, and it is. Not sure if you have acknowledged that...
  • Chad La Guardia
    Chad La Guardia over 13 years
    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.
  • Vishy
    Vishy over 13 years
    @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.
  • jjnguy
    jjnguy over 13 years
    @Peter, well you don't give anonymous classes names. But I suppose they do get named.
  • rsenna
    rsenna over 13 years
    @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!
  • Chad La Guardia
    Chad La Guardia over 13 years
    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
    Chad La Guardia over 13 years
    @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.
  • Tom Anderson
    Tom Anderson over 13 years
    @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.
  • Ninja
    Ninja over 13 years
    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
    Ninja over 13 years
    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?
  • Chad La Guardia
    Chad La Guardia over 13 years
    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.
  • Hariprasath
    Hariprasath about 10 years
    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.
  • Thor
    Thor over 8 years
    @ChadLaGuardia great explaination! straight to the point!
  • Marian Paździoch
    Marian Paździoch about 8 years
    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)
  • Admin
    Admin about 8 years
    I would say no... Because anonymous implements the interface... But you dont have implements keyword
  • Kasun Siyambalapitiya
    Kasun Siyambalapitiya almost 8 years
    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 () {
  • SMBiggs
    SMBiggs almost 8 years
    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.
  • Sargam Modak
    Sargam Modak over 7 years
    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.
  • Admin
    Admin over 7 years
    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.
  • Ram
    Ram almost 6 years
    If this anonymous class ProgrammerInterview were created inside a main() method then we could access it's method read() by calling p.read().
  • Karthick K
    Karthick K about 3 years
    This is just what I needed.