interface abc
{
...
}
Suppose I have methods which have a return type of Object and interface type abc.
class xyz
{
Object meth ()
{
...
}
abc meth2()
{
...
}
public static void main (String args[])
{
xyz x = new xyz() ;
Object a = x.meth() ;
abc c = x.meth2() ;
}
}
I don't want to implement the interface abc . The reference variable c is of type abc but what is the object type for c ? We cannot create objects of an interface , so what it could possibly be ?
For example : sup s = new sub() ; // where sub is subclass of sup . Here sup is the return type and sub is the object type .
3 Answers 3
The underlying type of c can be anything that implements abc. The actual type depends on your implementation of meth2.
"But in my code, nothing implements abc though!" you said. If nothing implements abc, meth2 cannot be implemented. It can never return a correct value because it can't create a type that is compatible with abc, if no types implement abc.
However, in meth2, you can create what is called an "anonymous class":
return new abc() {
// all the methods required by abc will be put here...
};
During compilation, this anonymous class will be turned into an inner class of the enclosing class that implements abc, and it will have the fully qualified name of something like yourpackage.EnclosingClass1ドル
Comments
In order to answer your question you must first think about the possible ways to write the meth2(). You must need to implement the ABC interface somewhere. You can do something like this:
ABC meth2() {
return new ABC(){
// Implement the methods that are defined in ABC interface
};
}
Comments
The method meth2 can only return null or an instance of a class implementing the interface abc.
meth2without creating an object ofabcunless you returnnull? In the latter case, the value ofcwill benull.Abcfor a type) and ident your codeabc, you must define a class that implements it (although it could be an anonymous class). I'm not clear on how you thought you could do anything useful without implementing the interface.Annotation(maybe more than one such class). It might be a private class buried somewhere in the Java runtime library.