Wednesday, March 2, 2011

Abstract class and Interface

1. normal class V.S. (abstract class and interface)
why do we need abstract class and interface: because there are some class which we never want to make a instance of.
E.g.
CONTENT
ARTICLE
BLOGS
REVIEW
content is the base class, we never want to make instance of it, so it could be an interface or abstract class. There is another example, CS571 OS class first assignment, we never want to make a instance of vehicle,  we only want to make instance of car or van. 

2. abstract class V.S. interface
Same properties:
1). we cannot make instance of them
2). they could have fields, but fields in interface by default public static final.
3). they could have abstract method. method in interface by default public and abstract. abstract class need to specify the abstract keyword. 
4). when you implement a interface or extend a abstract class. you have to provide the class definition in the derived class. In other words, all the abstract class in base class need to be implemented in the derived class if the derived class is a normal class. 
Different properties: 
1). interface only contains public abstract method by default. abstract class could contain 0 or many abstract method, it also could contain normal method with detailed method definition. if the class contains one or more abstract method, it must be qualified as abstract, otherwise compiler will give you an error message. 
2). interface has multi-inheritance. but abstract doesn't. 
3). interface use implements keyword; abstract use extends keyword.

3. When to use interface and when to use abstract class?
Take the content, blog, article, review example above, suppose content has an "publish" behavior. if the "publish" has some default behavior applies to everyone, we should use abstract class for content. if there is no default behavior for "publish" and every derived class need to implemented their own, we should use interface.Also, there is great article discussion at this link
Another great example is the first assignment of CS571. Runable is an interface,  Vehicle is an abstract class implement Runnable. Car and Van are derived class from Vehicle. 

No comments: