开发者

Reference variables for behavior interface types in Java

I'm reading Head First Design Patterns and have some understanding in Java. It starts by encapsulating things that vary from your class and putting them in a seperate interface, as opposed to putting those functionality in the subclass. The example they give is an abstract Duck class that can quack or fly depending on the duck. They have an interface for quack and fly (QuackBehavior and FlyBehavior interfaces), and then implement those interfaces in other classes.

In the example, they have the abstract duck class as follows

public abstract class Duck {
   QuackBehavior quackBehavior;
   FlyBehavior flyBehavior;
.....
}

I guess what is new to me is having an instance variable that is of the interface type. I never learned that before but I'm assuming it's valid? I guess I'm more familiar with having an instance variable of a concrete class. Are there any rules about having instance variables of classes/interfaces开发者_开发知识库 like this? Thanks.


It is valid, and a common practice.

It doesn't matter what the instance variable is. It is even preferred to use interfaces where possible. For example always define variables of type List and not ArrayList

Otherwise how would you be able to have different behaviours? Now you can assign both LowFlyBehaviour and HighFlyBehaviour to the field, and thus different instance of Duck can have different flying behaviours. If the field was either of these concrete types, this would not be possible.


Yes, it's valid. The only rules the apply are the same the apply for any other type; namely that you can only assign something that implements the declared interface. You have probably seen or even used a similar syntax before without realizing it, like:

List<String> list = new ArrayList<String>();
Serializable s = new Object();


If you declare a field as an interface type, the filed will be able to hold any class that implements the interface.

It's a normal field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜