Reputation: 29
I tried to create a class that extended File class (java.io.File
) and implement TreeNode interface like below:
public class mTreeNode extends File implements TreeNode{}
and tried to implement TreeNode methods but a conflict occurred.
public String getParent(){}
on File class has conflict with public TreeNode getParent()
on TreeNode interface on return type.
How can we solve it ? (for example why can't use Object class for return type !)
Finally I decided use a file object on my class.
Upvotes: 0
Views: 1315
Reputation: 12883
Classes that implement interfaces may declare covariant return types. So the return types in classes that implement interfaces must either match the interface or be a sub-class of the interface.
e.g.
class Foo {
public String toString() {
return "foo";
}
}
interface Interface {
Foo getFoo();
}
class Bar extends Foo {
public String toString() {
return "bar";
}
}
class Concrete implements Interface {
public Bar getFoo() { // <============= Covariant return type
return new Bar();
}
}
public class Example {
public static void main(String[] args) {
System.out.println(new Concrete().getFoo());
}
}
The class will print bar
.
Upvotes: 1