aps
aps

Reputation: 2472

Returning a subclass type object instead of superclass type object as demanded by interface

I have a class called Node and another class called ClassicNode which extends Node. Now I have an interface AgentInterface implemented by ClassicNode class. The interface states that there must be a method

Node selection();

As you can see, the return type should be of type Node. But in the class ClassicNode can I implement it like this instead:-

ClassicNode selection(){
    //Code
}

Will this satisfy the interface? (since ClassicNode inherits Node)

Upvotes: 0

Views: 826

Answers (2)

Chris Cheung
Chris Cheung

Reputation: 21

So,why don't you do a experiment? less work to do. you can just add annotation @Override upon the signature of your Method, then try to compile the code, if successfull, means that works, or failure.

Upvotes: 2

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

Yes; it's called covariant return. Note, though, that you cannot do the same thing with parameters; they must match exactly.

Upvotes: 5

Related Questions