Search code examples
javainterfaceupcasting

Java upcasting and downcasting by interfaces


This is probably a dumb question but I need to know. I have an interface as

import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsync;

public interface AsyncClient extends AmazonDynamoDBAsync{

}

And I have a ClientCreator class which has the method

import com.company.clients.AsyncClient;
public class ClientCreator {
        public static AsyncClient getAsyncClient() throws FileNotFoundException, IllegalArgumentException, IOException{
            AmazonDynamoDBAsync client = new AmazonDynamoDBAsyncClient(getCredentials());
            client.setRegion(getRegion());
            return (AsyncClient)client;
        }
        .
        .
        .

Here AmazonDynamoDBAsyncClient implements AmazonDynamoDBAsync and AsyncClient extends AmazonDynamoDBAsync, but this code would not work and throws

com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClient cannot be cast to com.company.clients.AsyncClient

but why?


Solution

  • Basically you've got the hierarchy like this:

             AmazonDynamoDBAsync 
                      ^
                      |
         -----------------------------
         |                           |
    AmazonDynamoDBAsyncClient   AsyncClient 
    

    And you are trying to cast AmazonDynamoDBAsyncClient instance to AsyncClient, which isn't possible. Those are siblings. Take it like this: "Apple" and "Banana" are both "Fruit", but an "Apple" is not a "Banana".