Is there more to an interface than having the correct methods

后端 未结 17 651
小鲜肉
小鲜肉 2020-11-22 13:37

So lets say I have this interface:

public interface IBox
{
   public void setSize(int size);
   public int getSize();
   public int getArea();
  //...and so          


        
17条回答
  •  隐瞒了意图╮
    2020-11-22 14:17

    Interfaces where a fetature added to java to allow multiple inheritance. The developers of Java though/realized that having multiple inheritance was a "dangerous" feature, that is why the came up with the idea of an interface.

    multiple inheritance is dangerous because you might have a class like the following:

    
    class Box{
        public int getSize(){
           return 0;
        }
        public int getArea(){
           return 1;
        }
    
    }
    
    class Triangle{
        public int getSize(){
           return 1;
        }
        public int getArea(){
           return 0;
        }
    
    }
    
    class FunckyFigure extends Box, Triable{
       // we do not implement the methods we will used the inherited ones
    }
    
    

    Which would be the method that should be called when we use

    
       FunckyFigure.GetArea(); 
    
    

    All the problems are solved with interfaces, because you do know you can extend the interfaces and that they wont have classing methods... ofcourse the compiler is nice and tells you if you did not implemented a methods, but I like to think that is a side effect of a more interesting idea.

提交回复
热议问题