Hi I have an abstract class in which I have some public methods and some abstract ones. I have the public so that they implement the common methods for the derived classes.
What is confusing me is why I will want to define a public abstract method instead of protected abstract. That makes no sense to me to define a public abstract method in abstract class.... because if is an abstract will be overridden, in the derived classes, but the same is if is defined as public but somehow it makes more sense to define it as protected as we know that we will override that in the derived classes.
Is it wrong to define the method as public abstract in an abstract class? Which is better and why?
For the same reason you want a public method in an object :) You just don't know the particular implementation at this stage. It is common in classes with very high level of abstraction, middlewares for example.
Edit: It is 100% legal. You just need to be sure that it is functionality that you want to expose to the rest of the world in every concrete implementation. Entry point methods (ex: start, execute, parse..) are usually of this kind.
It depends on what you want to achieve. For example, you have a
Television
class that has 3 methods,TurnOn
,TurnOff
, andDraw
.You only want clients to
TurnOn
orTurnOff
the TV but only its subclass should know what and how toDraw
on the screen. So,Television
will look more or less like below.Then each company has its own implementation.
Clients can
TurnOn
orTurnOff
a TV but cannotDraw
anything on the screen.The Abstract Class itself has to be as accessible as the Classes, which inherit from it. So if the inherited Classes are Public, the Abstract Class has to be public too.
Public Abstract has the same Idea like other Public Methods: If you have a Abstract Class, you will pass this arround. So if this Method should get called from outside, it's public. If the method is just for communication between Child and Parent, protected is the way to go. Easy example, see the Main-Method as the user of the abstract class: