Java - Method name collision in interface implementation

前端 未结 7 1491
渐次进展
渐次进展 2020-11-22 13:23

If I have two interfaces , both quite different in their purposes , but with same method signature , how do I make a class implement both without being forced to write a sin

7条回答
  •  忘掉有多难
    2020-11-22 13:56

    There's no real way to solve this in Java. You could use inner classes as a workaround:

    interface Alfa { void m(); }
    interface Beta { void m(); }
    class AlfaBeta implements Alfa {
        private int value;
        public void m() { ++value; } // Alfa.m()
        public Beta asBeta() {
            return new Beta(){
                public void m() { --value; } // Beta.m()
            };
        }
    }
    

    Although it doesn't allow for casts from AlfaBeta to Beta, downcasts are generally evil, and if it can be expected that an Alfa instance often has a Beta aspect, too, and for some reason (usually optimization is the only valid reason) you want to be able to convert it to Beta, you could make a sub-interface of Alfa with Beta asBeta() in it.

提交回复
热议问题