Mahyar Ina
Mahyar Ina

Reputation: 29

Java override conflict - same name with different return type

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

Answers (2)

BillRobertson42
BillRobertson42

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

Makoto
Makoto

Reputation: 106508

Since TreeNode is an interface, you are required to implement that method with its exact signature. It's a contract between the class that implements it and the outside world that is enforced by the compiler.

You can read more about it here.

Upvotes: 2

Related Questions