【问题标题】:Casting implemented class with interface using this operator使用此运算符使用接口转换实现的类
【发布时间】:2012-05-08 14:27:20
【问题描述】:
interface iMyInterface {
    public iMethod1();
}

public class cMyClass implements iMyInterface{
    public iMethod1() {
        System.out.println("From Method1");
    }
    protected iMethod2() {
        System.out.println("From Method2");
    }
}

class AppMain
{
    iMyInterface i=new cMyClass();
    public static void main(){
    i.iMethod1();
    ((cMyClass)i).iMethod2();
    }
}

这会产生如下输出

来自方法1

从方法2

因为接口对象被强制转换为该类

但我的问题是我不能在以下情况下进行投射

class AppMain
{
    iMyInterface i=new cMyClass();
    public static void main(){    
    i.iMethod1();
    this.((cMyClass)i).iMethod2();
    }
}

Eclipse IDE 显示以下错误: 标记“.”的语法错误,此标记后应有标识符。

我不明白这个 无论哪种方式,我都访问相同的字段。

【问题讨论】:

    标签: java interface casting this


    【解决方案1】:

    你只是在错误的点上施法。你想要:

    ((cMyClass) this.i).iMethod2();
    

    并不是说您有 this 在您的示例中像 main 这样的静态方法中引用...

    (另请注意,您的类型等均不遵循 ​​Java 命名约定...)

    【讨论】:

      【解决方案2】:

      试试

      ((cMyClass)(this.i)).iMethod2();
      

      你看,你的this 里面没有(cMyClass)i,它只有一个i。所以你得到i (this.i) 并将它转换成你想要的任何东西。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 2023-03-17
        • 2011-08-22
        • 1970-01-01
        相关资源
        最近更新 更多