Can we create an instance of an interface in Java?
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.
Related videos on Youtube
Ninja
Updated on July 05, 2022Comments
-
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 over 13 yearsAnonymous classes don't have names....anonymous
-
rsenna over 13 yearsHe's asked if his example was correct, and it is. Not sure if you have acknowledged that...
-
Chad La Guardia over 13 yearsThe 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 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 over 13 years@Peter, well you don't give anonymous classes names. But I suppose they do get named.
-
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 interfaceTest
. I know your intentions are good, but if you want to correct someone, please do it right! -
Chad La Guardia over 13 yearsHmmm, 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 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 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 over 13 yearsThanks 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 over 13 yearsBut 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 over 13 yearsIf 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 about 10 yearsthe 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 over 8 years@ChadLaGuardia great explaination! straight to the point!
-
Marian Paździoch about 8 yearsIs 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 about 8 yearsI would say no... Because anonymous implements the interface... But you dont have implements keyword
-
Kasun Siyambalapitiya almost 8 yearsis 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 almost 8 yearsThis 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 over 7 yearsin 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 over 7 yearsBut 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 almost 6 yearsIf this anonymous class
ProgrammerInterview
were created inside amain()
method then we could access it's methodread()
by callingp.read()
. -
Karthick K about 3 yearsThis is just what I needed.