使用此运算符使用接口强制实现类

时间:2012-05-08 14:27:21

标签: java interface casting this

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();
    }
}

这产生如下输出

来自Method1

来自Method2

becoz接口对象被转换为该类

但我的问题是我不能在下面的案例中施展

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

Eclipse IDE显示以下错误: 令牌“。”上的语法错误,此令牌后预期的标识符。

我不明白这一点 在任何一种方式我访问相同的领域。

2 个答案:

答案 0 :(得分:4)

你只是在错误的点上投掷。你想要:

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

并非您 this在您的示例中使用main这样的静态方法来引用...

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

答案 1 :(得分:1)

尝试

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

您看,您的this中没有(cMyClass)i,只有i。所以你得到ithis.i)并将其投射到任何你想要的地方。

相关问题