The next thing that beginners wonder after understanding what interfaces and abstract classes look like __ How should each be used properly? __ I think that is the case.
--The interface defines the method API in __ for the __caller --Abstract classes implement some in __ for those who implement __ child classes
In short, that's it.
Implement the interface for the class you want to call using polymorphism.
The user should not declare variables of abstract class type. Let's declare a variable as an interface type.
AbstractFooBar = new FooBar(); // NG
IFooBar = new FooBar(); // OK
You should also not define methods that use abstract classes as formal argument types. Let's specify the interface type.
void fooMethod(AbstractFooBar fooBar); // NG
void fooMethod(IFooBar fooBar); // OK
So what if you want to use polymorphism for the child classes of an abstract class? Because the question seems to arise. In that case, it looks like the following.
That way, the user should always call via the IFooBar interface, and For those who implement the IFooBar interface, You can choose to extend AbstractFooBar or implement IFooBar directly, Everyone will be happy.
Recommended Posts