Picking up an OOP(2) -JAVA-Interface

来源:互联网 发布:顶尖文案网 知乎 编辑:程序博客网 时间:2024/05/21 09:56

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

  1. Note that all interface methods are public. Do not need to put public in the front.
  2. Interface method can not have default implementation.
  3. Can’t have instance variable. However can have static final.
  4. Can extends from other interface.
  5. 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.
  6. A class implement certain interface, it has to override all methods in that interface
  7. interface can be a type in passing into a method. (need to see more in detail)

Callback Pattern

0 0