When to use Abstract Classes and Interfaces? [closed]

ⅰ亾dé卋堺 提交于 2019-12-13 08:37:29

问题


Why we use Interface?

When we implement one interface we have to write definition for methods of that interface. So, what is need to implement interface? We can directly write methods in the class.

Thanks :)


回答1:


an example might be useful for you,see below scenarios.

1.class A extends B{
..
..
..
}

when A extends B and you are creating A new class C ,you can not make A extend C along with B So go for Interface.

2.class A implements B {
..
..
}

If you add a new method in B and it(B) is implemented by 100 classes ,it is hard to implement new method in all classes,so go for abstract class and add new method with skeleton implementation.

for further help read Effective Java by Joshua Bloch.




回答2:


This more like interview question -

Decission about when to use what is being arround for long and is one of those discussions with a lot of people having its opinion or backing up this or that idea. I think there's a basic rule that works almost everytime: Use abstract clases and inheritance if you can make the statement "A is a B". Use interfaces if you can make the statement "A is capable of [doing] as", or also, abstract for what a class is, interface for what a class can do.

Por example, we can say a triangle is a polygon but it makes no sense to say a triangle is capable of being a polygon.

Anyway, as ever, the rule of thumb for this is: use your common sense. Sometimes an interface just fit much better, even if the above rule tells you the contrary, if that's it just use the interface (after considering consequences of course).




回答3:


you have one method which is used by N number of classes.If definition are differ from each class use Interface.

Let say one method is similar for 50 classes and another 50 classes have different behavior means use Abstract class.There you define the method.

And use for first 50 classes and remaining 50 classes have different behavior so override the existing method according to the class behavior.
Example

Interface Graphics
{
   void size();
   void draw();

}

Class Rectangle implements Graphics
{
     void size()
     {
        x=10;
        y=10;
     }
    void draw()
    {
       .....
    }

}
class Triangle implements Graphics
{
   void size()
     {
        x=10;
        y=10;
     }
    void draw()
    {
       .....
    }

}

so both the size are same for both classes then use abstract

abstract class Graphics
{
   void size()
     {
        x=10;
        y=10;
     }
    abstract void draw();

}

Then if any class extends this class the size is similar and only define the draw() If some classes needs different position then override the size.



来源:https://stackoverflow.com/questions/10443344/when-to-use-abstract-classes-and-interfaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!