对接口的对象进行显式转换。括号的用法是什么 [英] Explicit casting on objects with interface. What's the use of parentheses

查看:374
本文介绍了对接口的对象进行显式转换。括号的用法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个类似的问题,但它并没有真正关注界面问题 - 问题关于投射对象括号

I have found a similar question, but it didn't really concern the interface issue - Issue about casting object brackets

public class Speak { /* Line 1 */

    public static void main(String[] args) { /* Line 2 */

        Speak speakIT = new Tell(); /* Line 3 */ 
        Tell tellIt = new Tell(); /* Line 4 */ 

        speakIT.tellItLikeItIs(); /* Line 5 */ 
        (Truth)speakIt.tellItLikeItIs(); /*Line 6 */ 
        ((Truth)speakIt).tellItLikeItIs(); /* Line 7 */ 
        tellIt.tellItLikeItIs(); /* Line 8 */ 
        (Truth)tellIt.tellItLikeItIs(); /* Line 9 */ 
        ((Truth)tellIt).tellItLikeItIs(); /* Line 10 */
    } 
}

class Tell extends Speak implements Truth {
    public void tellItLikeItIs() { 
        System.out.println("Right on!"); 
    }
}

interface Truth {     
    public void tellItLikeItIs()
}

第7,8和10行是正确的。我得到数字7,但为什么不是数字6和9正确,而不是8和10?我们如何才能显式地转换到一个接口?

Line 7, 8 and 10 are the correct ones. I get number 7, but why isn't number 6 and 9 correct instead of 8 and 10? And how come we can explicitly cast to an interface? what logic is behind the use of parentheses of answer 8 and 10?

推荐答案

(Truth) tellIt.tellItLikeItIs()

调用 tellItLikeItIs() tellIt 对象上,并将此方法返回的值转换为 Truth

calls tellItLikeItIs() on the tellIt object, and casts the value returned by this method to Truth.

((Truth) tellIt).tellItLikeItIs()

casts tellIt Truth ,然后调用 tellItLikeItIs

casts tellIt to Truth, and then calls tellItLikeItIs() on the object.

这篇关于对接口的对象进行显式转换。括号的用法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆