简体   繁体   中英

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 ?

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".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM