java是否支持像c#这样的显式接口实现? [英] Does java support explicit interface implementation like c#?

查看:155
本文介绍了java是否支持像c#这样的显式接口实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试过这样做:

interface pet {
    void sleep();
}
interface robot {
    void sleep();
}

public class roboGarfield implements pet , robot {

    /*
     * this gives error
    void pet.sleep(){

    }
    */

    @Override
    public void sleep() { System.out.println("this isn't really specific.."); }

    public static void main(String[] args){
        roboGarfield t = new roboGarfield();
        t.sleep();
        ((pet)t).sleep(); // similar to C# 
        ((robot)t).sleep();
    }    
}

但即使我可以投出 roboGarfeild 对象 pet 机器人类型,我不能显式实现,如c#。

But even though i can cast the roboGarfeild object to its pet or robot type , i cant do an explicit implementation like c#.

我做错了什么?或者只是在java中不支持?

Anything i'm doing wrong ? or is it just not supported in java ?

编辑:因此,java不支持像C#这样的显式接口实现。但是对于无法避免的情况,Holger的委托方法似乎就好了。

So , java doesn't support explicit interface implementation like C#. But for cases where they can't be avoided , Holger's delegate method seems like the way out.

感谢所有回复。

推荐答案

public class roboGarfield implements pet , robot {

     @ovveride
     public void  sleep(){
         //here you are implementing sleep method
         //But satisfying both pet and robot interface's sleep method.
     }

执行此操作时,在java中,单个实现适用于接口。 AFAIK, NO 解决。

When you do this , in java the single implementation works for the both interface. AFAIK, NO work around.

这篇关于java是否支持像c#这样的显式接口实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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