Answer the question
In order to leave comments, you need to log in
Abstract classes and interfaces - when to use one or the other?
Hello
As far as I understand, abstract classes are used to highlight the generality in the implementation, and interfaces - for the generality in behavior. But why can't the generality of behavior be isolated in abstract methods?
For example, there is an abstract class animal with a method to breathe. Descendants implement an interface with a "make a sound" method. But why can't this method be taken as abstract in the "animal" class? When should one or the other be used?
Answer the question
In order to leave comments, you need to log in
As for me, these associations from the real world only complicate the understanding of OOP.
An interface is a description of the methods for accessing an object.
An abstract class is a selection of common methods and properties of classes.
It all depends on what you want. And in general, there are many options with “optional” functionality (for simplicity, I write in Java).
1. "Type according to OOP".
class Animal {}
class Dog extends Animal {
public void doSound() {}
}
interface Vocal {
void doSound();
}
class Animal {}
class Dog extends Animal implements Vocal {
@Override
public void doSound();
}
if (animal instanceof Vocal)
((Vocal)animal).doSound().
class Animal {
protected:
void doSound();
};
class Dog : public Animal {
public:
using Animal::doSound;
};
protected __property Caption
. And in 99% of cases this is enough: the title is displayed somewhere - pull it out. I have a question with automatic translation of forms. Either connect introspection, or Public Morozov (in Delphi/Builder there is introspection and an additional published access right that connects a property to it). I did not suffer and did the second. public class Dog extends Animal {
@Override
public void doSound() { super.doSound(); }
}
public static void main(String[] args) {
Animal an = new Animal();
an.doSound(); // protected!
}
class Animal {
public boolean isVocal() { return false; }
public void doSound() {}
}
class Animal {
public Vocal getVocal() { return null; }
}
Interface - when you need to work uniformly with different objects that have the same logical purpose (entity repositories, for example).
Abstract class - when you need to define some uniform behavior for all derived objects, as well as differences in behavior - abstract methods.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question