Issue in returning interface as return type in Java
I have the following code:
Filename: A.java
package test1
public interface A {
int get();
int set();
}
Filename: B.java
package test1
public class B implements A {
int get() {
...
}
int set() {
....
}
}
Filename: C.java
package test2
import test1.A;
import test1.B;
publc class C {
public A getNum() {
B test = null;
return(test);
}
}
When I compiled the above code in Eclipse--> Sample Java Project, It is working fine. But when I compil开发者_StackOverflowed the same code in Android, It is throwing the following error:: Method C.getNum returns unavailable type A;
Please let me know, where I am going wrong.
Thanks in advance, Kranti
Inteface
and Implements
are not java keywords. You should use interface
and implements
instead. Java is case sensitive. Type A
is unavailable on the class path due to other compilation errors.
the following code should work:
public class Test {
interface A {
int get();
int set();
}
class B implements A {
@Override
public int get() {
return 0;
}
@Override
public int set() {
return 0;
}
}
class C {
public A getNum(){
A a = new B();
return a;
}
}
}
I've produced that code based on your example. But you know I cannot imagine what this code is useful for.
Assuming A.java, B.java are in test directory and C.java is in the root directory the above code has many issues
- Interface and Implements should be small caps i.e "interface" and "implements"
- interface methods are public even if not declared. So when implementing it in B both get and set should be public
- A.java and B.java should have package test; as the first line
- You need to import test.A; import test.B;
- There is no class declaration for C
- B test = 0; is wrong. It should be either B test = null; or B test = new B(); depending on what you plan to use. 0 is an integer and can't be cast to B
- return B is not valid as B is a class name. You probably intended return test;
Here's a modified code
A.java
package test;
public interface A {
int get();
int set();
}
B.java
package test;
public class B implements A {
public int get() {
return 0;
}
public int set() {
return 0;
}
}
C.java
import test.A;
import test.B;
public class C {
public A getNum() {
B test = new B();
return test;
}
}
The problem I see is just to mention the package declaration i.e. package test1 in the interface A file.
精彩评论