user1812652
user1812652

Reputation: 33

Java Interface - Object to class typecasting

I have an interface that looks something like

public interface KeyRetriever {

public Object getKey(Object obj);

}

I want the implementation to be something like

CustomerTypeKeyRetriever (Implementation class)

public String getKey(Customer customer) {
    return null;
}

How can I achieve this. Currently it throws a compilation error - "The type CustomerTypeKeyRetriever must implement the inherited abstract method KeyRetriever.getKey(Object)"

Upvotes: 2

Views: 678

Answers (3)

PermGenError
PermGenError

Reputation: 46408

use generics in your interface declaration.

public interface KeyRetriever<T> {

public Object getKey(T obj);
}

now in your subclass you can implement it

 public class CustomerTypeKeyRetriever implements KeyRetriever<String> {
  public String getKey(String str){
        //your implementation

  }
 }

Upvotes: 4

Santosh Gokak
Santosh Gokak

Reputation: 3411

Your implementation should have method like

@Override
    public Object getKey(Object obj) {
        // TODO Auto-generated method stub
        return null;
    }

I would also put a @Override annotation to on all my implementaion method so that compiler can catch any method changes/conflicts in future in case API's change.

In case you want generified interface, below should work (this is what i think you might want)

public interface KeyRetriever<T> {
    public Object getKey(T obj);
}

public class CustomerTypeKeyRetriever implements KeyRetriever<Customer> {

    @Override
    public String getKey(Customer obj) {
        // TODO Auto-generated method stub
        return null;
    }

}

Here the return type can be any subclass of Object since java supports covariant return types.

Upvotes: 0

MD. Sahib Bin Mahboob
MD. Sahib Bin Mahboob

Reputation: 20524

Lets say you have a Person interface :

public interface Person {}

Your Customer and Employee classes implemented that :

public class Customer implements Person {/* Your class body */}
public class Employee implements Person {/* Your class body */}

Then you can change your interface like this :

public interface KeyRetriever {

public String getKey(Person person);
}

And in your Customer class you then have to change like this :

public String getKey(Person perosn) {
   return null;
}

Hope that helps . Happy coding :)

Upvotes: 0

Related Questions