Do interfaces solve the “deadly diamond of death” issue?

后端 未结 6 736
长情又很酷
长情又很酷 2021-01-03 03:02

Do interfaces solve the deadly diamond of death problem?

I don\'t think so, for example:

// A class implementing two interfaces Interface1 and Interf         


        
6条回答
  •  青春惊慌失措
    2021-01-03 03:30

    An interface can't have attributes. When you write this:

    public interface Foo {
        int x;
    }
    

    Under the hood it implicitly gets converted to a constant, something like this:

    public interface Foo {
        public static final int x;
    }
    

    Let's say you have another interface with a similarly named constant:

    public interface Bar {
        int x;
    }
    

    And if you were to use the x value in a class that implements both Foo and Bar you'll have to qualify those constants, leaving no room for ambiguities, like this:

    public class Baz implements Foo, Bar {
        private int y = Foo.x + Bar.x;
    }
    

    So no diamond in here. Anyway, declaring constants in an interface is frowned upon nowadays, most of the time you're better off using an enumeration for the same effect.

提交回复
热议问题