Interfaces and abstract classes provide more structured way to separate interface from implementation.

  the abstract class, which is a kind of midway step between an ordinary class and an interface.

Abstract classes and methods

  abstract void f();

  A class containing abstract methods is called an abstract class. If a class contains one or more abstract methods, the class itself must be qualified as abstract.

  It's possible to make a class abstract without including any abstract methods. This is useful when you've got a class in which it doesn't make sense to have any abstract methods, and yet you want to prevent any instances of that class.

  Abstract classes are also useful refactoring tools, since they allow you to easily move common methods up the inheritance hierarchy.

Interfaces

  The interface keyword produces a completely abstract class, one that provides no implementation at all.

  An interface says, "All classes that implement this particular interface will look like this."

  The interface is used to establish a "protocol" between classes.

  interface allowed multiple inheritance

  An interface can also contain fields, but these are implicitly static and final.

  You can choose to explicitly declare the methods in an interface as public, but they are public even if you don't say it. So wnen you implement an interface, the methods from the interface must be defined as public.

Complete decoupling

  Creating a method that behaves differently depending on the argument object that you pass it is called the Strategy design pattern. The method contains the fixed part of the algorithm to be performed, and the Strategy contains the part that varies

  The Strategy is the object that you pass in, and it contains code to be executed.

  public static void process(Processor p, Object s) {

    p.process(s);

  }

  public static void main (String[] args) {
    process(new Upcase(),s);

    process(new Downcase(),s);

  }

  However, you are often in the situation of not being able to modify the classes that you want to use. In these cases, you can use the Adapter design pattern.

  class FilterAdapter implements Processor {

    Filter filter;

    public FilterAdapter (Filter filter) {

      this.filter = filter;

    }

    public String name () { return filter.name();}

    public Waveform process (Object input) {

      return filter.process((Waveform)input);

    }

"Multiple inheritance" in Java

  A class can only extends one class, and can implements one or more interface

  When you combine a concrets class with interfaces this way, the concrete class must come first, then the interfaces.

  The resons for interfaces:

    1. to upcast to more than one base type.

    2. (the same as using an abstract base class) to prevent the client programmer from makig an object of this class and to establish that it is only an interface.

  In fact, if you know somethins is going to be a base class, you can consider making it an interface.

Extending an interface with inheritance  

  You can easily add new method declarations to an interface by using inheritance, and you can also combine several interfaces into a new interface with inheritance.

  Name collisions when combining interfaces

  overloaded methods cannot differ only by return type.

  Using the same method names in different interfaces that are intended to be combined generally causes confusion in the readability of the code, as well. Strive to avoid it.

Adapting to an interface

  A common use for interfaces is the Strategy design pattern.

Fields in interfaces  

  Because any fields you put into an interface are automatically static and final, the interface is a convenient tool for creating groups of constant values. Before Java SE5, this was the only way to produce the same effect as an enum.

  The fields in an interface are automatically public.

  Initializing fields in interfaces

  Fields defined in interfaces cannot be "blank finals", but they can be initialized with non-constant expressions.

  the fields, of course, are not part of the interface. The values are stored in the static storage area for that interface.

Nesting interfaces

  nesting an interface, these can have public 、package-access or private visibility.

  Implementing a private interface is a way to force the definition of the methods in that interface without adding any type information.

  

package interfaces.nesting;

class A {
  interface B {
    void f();
  }

  public class BImp implements B {
    public void f() {
    }
  }

  private class BImp2 implements B {
    public void f() {
    }
  }

  public interface C {
    void f();
  }

  class CImp implements C {
    public void f() {
    }
  }

  private class CImp2 implements C {
    public void f() {
    }
  }

  private interface D {
    void f();
  }

  private class DImp implements D {
    public void f() {
    }
  }

  public class DImp2 implements D {
    public void f() {
    }
  }

  public D getD() {
    return new DImp2();
  }

  private D dRef;

  public void receiveD(D d) {
    dRef = d;
    dRef.f();
  }
}

interface E {
  interface G {
    void f();
  }

  // Redundant "public":
  public interface H {
    void f();
  }

  void g();
  // Cannot be private within an interface:
  // ! private interface I {}
}

public class NestingInterfaces {
  public class BImp implements A.B {
    public void f() {
    }
  }

  class CImp implements A.C {
    public void f() {
    }
  }

  // Cannot implement a private interface except
  // within that interface’s defining class:
  // ! class DImp implements A.D {
  // ! public void f() {}
  // ! }
  class EImp implements E {
    public void g() {
    }
  }

  class EGImp implements E.G {
    public void f() {
    }
  }

  class EImp2 implements E {
    public void g() {
    }

    class EG implements E.G {
      public void f() {
      }
    }
  }

  public static void main(String[] args) {
    A a = new A();
    // Can’t access A.D:
    // ! A.D ad = a.getD();
    // Doesn’t return anything but A.D:
    // ! A.DImp2 di2 = a.getD();
    // Cannot access a member of the interface:
    // ! a.getD().f();
    // Only another A can do anything with getD():
    A a2 = new A();
    a2.receiveD(a.getD());
  }
}

  The rules about interfaces-- that all interfaces elements must be public--are strictly enforces here, so an interface nested within another interface is automatically public and cannot be made private.

  Notice that when you implement an interface, you are not required to implement any interfaces nested within. Also, private interfaces cannot be implemented outside of their defining classes.

Interfaces and factories

  An interfaces is intended to be a gateway to multiple implementations, and a typical way to produce objects that fit the interface is the Factory Method design pattern.

  You call a creation method on a factory object which produces an implementation of the interface--this way, in theory, your code is completely isolated from the implementation of the interface.

Summary

  Almost anytime you create a class, you could instead create an interface and a factory.

  Interfaces should be something you refactor to when necessary, rather than installing the extra level of indirection everywhere, along with the extra complexity.

  An appropriate guideline is to prefer classes to interfaces. Start with classes, and if it becomes clear that interfaces are necessary, then refactor. Interfaces are a great tool, but they can easily be overused.

  

  

Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(九)之Interfaces的更多相关文章

  1. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(七)之Access Control

    Access control ( or implementation hiding) is about "not getting it right the first time." ...

  2. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(六)之Initialization & Cleanup

    Two of these safety issues are initialization and cleanup. initialization -> bug cleanup -> ru ...

  3. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十三)之Strings

    Immutable Strings Objects of the String class are immutable. If you examine the JDK documentation fo ...

  4. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(二)之Introduction to Objects

    The genesis of the computer revolution was a machine. The genesis of out programming languages thus ...

  5. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十四)之Type Information

    Runtime type information (RTTI) allow you to discover and use type information while a program is ru ...

  6. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十二)之Error Handling with Exceptions

    The ideal time to catch an error is at compile time, before you even try to run the program. However ...

  7. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十一)之Holding Your Objects

    To solve the general programming problem, you need to create any number of objects, anytime, anywher ...

  8. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十)之Inner Classes

    The inner class is a valuable feature because it allows you to group classes that logically belong t ...

  9. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(八)之Polymorphism

    Polymorphism is the third essential feature of an object-oriented programming language,after data ab ...

随机推荐

  1. iOS开发:判断iPhone是否是刘海屏iPhoneX、iPhoneXR、iPhoneXs、iPhoneXs Max等

    保证能判断,呕心沥血,不行切JIJI 方法一 Objective-C // iPhoneX.iPhoneXR.iPhoneXs.iPhoneXs Max等 // 判断刘海屏,返回YES表示是刘海屏 - ...

  2. 泛微E-cology OA 远程代码执行漏洞

    分析文章:https://dwz.cn/bYtnsKwa http://127.0.0.1/weaver/bsh.servlet.BshServlet 若存在如上页面,则用下面数据包进行测试. POS ...

  3. OFD电子证照模版制作工具使用说明

    每一类电子证照都具有相同板式,不同的电子证照之间只是文字.图片的差异.生成电子证照常用的方式就是采用模版批量生成. 本软件可以方便的设计证照模版.服务端根据模版生成电子证照,不同种类的电子证照生成逻辑 ...

  4. C 2014年笔试题

    1.指出程序中的错误,说明原因并修正 int *p,*q; p=malloc(sizeof(int)*20); q=malloc(sizeof(int)*10); … q=p; … free(p); ...

  5. python爬取网站页面时,部分标签无指定属性而报错

    在写爬取页面a标签下href属性的时候,有这样一个问题,如果a标签下没有href这个属性则会报错,如下: 百度了有师傅用正则匹配的,方法感觉都不怎么好,查了BeautifulSoup的官方文档,发现一 ...

  6. 用c写的简单的日历(学习模块划分)

    简单日历 ​ 主要目的是学习函数模块划分,成品大概是这样,加了一些花里胡哨的东西(/▽\) ​ 分三个模块,主函数.c 显示.c 计算.c 与.h 文件 有两种实现方式,区别在于是否以数组在模块之间传 ...

  7. 5L-链表导论心法

    链表是比数组稍微复杂一点的数据结构,也是两个非常重要与基本的数据结构.如果说数组是纪律严明排列整齐的「正规军」那么链表就是灵活多变的「地下党」. 关注公众号 MageByte,有你想要的精彩内容. 链 ...

  8. [阿里云-机器学习PAI快速入门与业务实战 ]课时1-机器学习背景知识以及业务架构介绍

    什么是机器学习? 机器学习指的是机器通过统计学算法,对大量的历史数据进行学习从而生成经验模型,利用经验模型指导业务. 目前机器学习主要在一下一些方面发挥作用: 营销类场景:商品推荐.用户群体画像.广告 ...

  9. test命令的使用以及判断语法

    test命令 Shell中的 test 命令用于检查某个条件是否成立,它可以进行数值.字符和文件三个方面的测试. 语法:test EXPRESSION 或者 [ EXPRESSION ] 字符串判断( ...

  10. FastText的内部机制

    文章来源:https://towardsdatascience.com/fasttext-under-the-hood-11efc57b2b3 译者 | Revolver fasttext是一个被用于 ...