Basics
前段时间和Yahoo的校招说我最近在往JAVA迁移,结果人家说那你讲讲Interface好了,一脸懵逼要是早一周看到这些多好。anyway知识是自己的,讲道理Yahoo除了新闻和天气预报好像也没什么增长点的样子hhh 废话不多说,这次讲讲自己对于Interface的理解。
有些概念呢起初拿到晦涩难懂,真正理解了意思呢就觉得啊哈,再找不出更准确描述这个概念的词了,比如说这里Interface
举个栗子:
public abstract class Door{
abstract void open();
abstract void close();
}
public interface Alarm{
void alarm();
}
public class AlarmDoor extends Door implement Alarm{
@override public void open(){};
@override public void close(){};
@override public void alarm(){};
}
abstract class is like blueprint, while object is the one actually build those blueprint. The interface on the other hand are similar functionality shared between objects. What I mean by similar functionality is that the interface only defines methods, while never implement a default one.
This is intuitive that if we have a interface Alarm which defines like 0 to many methods, then we say a AlarmDoor can implement Alarm. While a clock can also Alarm, whereas they clearly inheritaged from different super classes.
Some thing to address briefly, specifically
- Note that all interface methods are public. Do not need to put public in the front.
- Interface method can not have default implementation.
- Can’t have instance variable. However can have static final.
- Can extends from other interface.
- Multiple implementation. This is extremely important. For JAVA does not support multiple inheritance for data security concern, while simplifies here. This also consist with ISP (Interface Segregation Principle). To separate different interface, make sure they don’t corrupt each other. Then implement as many as needed in specific class.
- A class implement certain interface, it has to override all methods in that interface
- interface can be a type in passing into a method. (need to see more in detail)