Google Search

Saturday, April 24, 2010

INTERFACE MEANS?

DEFINTION: Well, I am a self-learn programmer. If you are a beginer, I believe you will get headache like me when you read tutorial written by experienced programmer explaining "interface" with professional words.
If you are beginner, I believe you will get more help from a tutorial written by a non-professional programmer like me.
So, what is inteface ? Like others, I will explain it by examples.
We have various shapes. Square, triangle and circle. There are many common porperties among them. Like, color,rotation, x,y etc. So, we can create a "Shape" class with methods as getColor(), getRotation()......etc.
After we have Shape Class, we start our jobs. Now, we need to create Square class, Circle class and Triangle class. Well, it is simple. Make Square class extends Shape, so Square class will inherit all those methods in Shape. Most of these methods like getColor(), getRotation()... etc, do not need additional codes. We use these methods defined in its Ancestor "Shape" class. We dont need any codes before we can use them. At most, we need small modification only. So does the Circle and Triangle class.
Now, we face another set of "common" methods. We need a method to show the area of the shape. Unlike the function getColor(), the formula to calculate area of square, circle or triangle are totally different from each other. It is impossible to write a general function in the "Shape" class to calculate the area. Thus, although we need a "common" function to show the area of various shape, in fact, there is nothing in common.
For example,
in class Square, we have getRectArea(){return (height*width);};
in class Circle, we have getCircleArea(){return (radius*Math.PI*Math.PI);};
in class Triangle, we have getTriangleArea(){return (height*widht/2);};
OK, that goes without any problems. But, are'nt they all serve as a method to calculate Area ? Good programmer will try to give all these methods the same name - for example "getArea". Other wise, we need Square.getRectArea() to know the area. Circle.getCircleArea() to know the area and Triangle.getTriangleArea() to get the area of triangle instance. Although the formula is different, a common method name means they function the same goal. And, that make them more like "the same kind" of thing.
Here comes the interface.
interface RegularShape
{
    var getArea();
 }
Lets modify our class Circle by :
class Circle extends Shape implements RegularShape{
......
}
After click "check syntax", Flash complains that, we should have a "getArea()" method.
So, we are hint, and we follow the hint. We rename our "getCircleArea" method to "getArea" method. Thus, we use getArea to get the area of a Circle instance instead of getCircleArea();
Also, we implements RegularShape to Square class. And we are forced to rename our getRectArea into getArea(). Same things happen to our Triangle class.
That is all about interface.

No comments:

referal link