When to use abstract classes and interfaces?

Why do we use the interface?

When we implement one interface, we must write a definition for the methods of this interface. So what is needed to implement the interface? We can write methods in the class directly.

Thanks:)

-1
source share
3 answers

An example may be useful to you, see the scripts below.

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

when A extends B and you create a new class C, you cannot make A extend C with B So go for Interface.

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

If you add a new method to B and it (B) is implemented in 100 classes, it is difficult to implement a new method in all classes, so go for the abstract class and add a new method from the skeleton.

for further help, read Effective Java from Joshua Bloch.

+1
source

you have one method that is used by N number of classes. If the definition is different from each class, use the interface.

Let's say one method is similar for 50 classes, and another 50 classes have different behaviors that use an abstract class. You define a method.

And use for the first 50 classes, and the remaining 50 classes have different behavior, so redefine the existing method in accordance with 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 sizes are the same for both classes and 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 defines only draw() If some classes need a different position, then override the size.

0
source

This is more like an interview question -

The decree on when to use what is cool now is one of those discussions with a large number of people who have their own opinion or support an idea. I think there is a basic rule that works almost every time: use abstract classes and inheritance if you can make the statement "A is B". Use interfaces if you can make the operator “A capable of [doing] how,” or also abstract to the class, an interface for what the class can do.

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

In any case, as always, the rule of thumb is: use your common sense. Sometimes an interface just fits a lot better, even if the above rule tells you otherwise if it just uses the interface (after considering the consequences, of course).

0
source

Source: https://habr.com/ru/post/1343600/


All Articles