R
R
Romi2021-07-19 09:49:24
PHP
Romi, 2021-07-19 09:49:24

Why not make an ordinary class instead of an abstract one, but with empty methods?

subject :)

I never used this feature - an abstract class - because I don't understand: why is it needed at all?

After all, I can simply not define the body of the method in the base ordinary class, and that’s all.

Or have I missed something in my reasoning?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Developer, 2021-07-19
@romicohen

An abstract class is needed so that it is not possible to create its instances, but only its descendant classes.
A simple example. Let's have an abstract Shape class with a Draw method; and there are its descendant classes Circle and Square.
So. We have the right to create instances of the Circle and Square classes, but we have no right to create an instance of the Shape, because it has no physical meaning. And even more so, we can’t implement the Draw method on the Shape in any way. Therefore, such a ban on abstract classes is made.
This is necessary so that the code is reliable and protected from the crooked hands of other programmers.

A
Alexander Skusnov, 2021-07-19
@AlexSku

If there are several brothers, then they must have a parent.
The parent (as an interface) declares a bunch of methods without an implementation, the implementation of the descendants is already specialized (therefore, there is nothing to describe in the parent).

After all, I can simply not define the body of the method in the base ordinary class, and that’s all.

Indeed, they do this: one part of the methods is defined on the parent, but not all.
But if no method is defined, then the question arises - is such an instance without methods needed? Here's the abstraction and solution: you can't make an instance.

R
res2001, 2021-07-19
@res2001

I don’t know how it works in PHP, but in principle, abstract classes force inheritors to override abstract methods. It is impossible to use abstract methods that have not been overridden - there will be an error.
In the case of an ordinary class and an empty method, you can easily use methods that are not overridden in the heir. There will be no effect from such use (the method does nothing), but there will be no error either.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question