Interfaces


Abstract classesand methods
Interfaces
However, an interface is more than just an abstract class taken to the extreme, since it allows you to perform a variation of "multiple inheritance" by creating a class that can be upcast to more than one base type.
To create an interface, use the interfacekeyword instead of the classkeyword. As with a class, you can add the publickeyword before the interfacekeyword ( but only if that interface is defined in a file of the same name). If you leave off the publickeyword, you get package access, so the interface is only usable within the same package. An interface can also contain fields, but these are implicitly static and final.
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.
“Multiple inheritance” in Java
When you combine a concrete class with interfaces thisway, the concrete class must come first, then the interfaces.
Extending an interfacewith inheritance
Name collisions when combining Interfaces
Adapting to an interface
Because you can add an interface onto any existing class in this way, it means that a method that takes an interface provides a way for any class to be adapted to work with that method.This is the power of using interfaces instead of classes.
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.
Initializing fields in interfaces
Since the fields are static , they are initialized when the class is first loaded, which happenswhen any of the fields are accessed for the first time.
Nesting interfaces
Interfaces may be nested within classes and within other interfaces.
As an added twist, interfaces can also be private, notice that when you implement an interface, you are not required to implementany interfaces nested within. Also, private interfaces cannot be implemented outside oftheir defining classes.
Interfaces and factories
















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值