简体   繁体   English

通过接口进行Java上传和下传

[英]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 我有一个ClientCreator类,它有该方法

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 这里AmazonDynamoDBAsyncClient实现了AmazonDynamoDBAsync,AsyncClient扩展了AmazonDynamoDBAsync ,但是这段代码无法正常工作并抛出

com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClient cannot be cast to com.company.clients.AsyncClient com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClient无法强制转换为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. 并且您正在尝试将AmazonDynamoDBAsyncClient实例转换为AsyncClient ,这是不可能的。 Those are siblings. 那些是兄弟姐妹。 Take it like this: "Apple" and "Banana" are both "Fruit", but an "Apple" is not a "Banana". 这样说:“苹果”和“香蕉”都是“水果”,但“苹果”不是“香蕉”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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