Reputation: 14145
If I have an abstract class like
public abstract class Player
{
//fields
private Sport _sport;
//properties
protected Sport Sport
{
get { return _sport; }
set { _sport = value; }
}
}
Is this protected access modifier redundant since abstract cannot be instantiated?
Upvotes: 6
Views: 9987
Reputation: 17
abstract class ProgressNotesDetail
{
}
internal class ProgressNotes : ProgressNotesDetail
{
}
Default Access modifier in Abstract class---- Internal
Upvotes: -2
Reputation: 150253
No, protected
in abstract class is not redundant because it makes the derived-implementing classes to "have"-derive:
protected Sport Sport
Instead of:
public Sport Sport
And if you used private
or removed the modifier completely, then sport
would be visible only for the abstract class itself.
For example:
public abstract class Player
{
// Changed to auto property to save some key strokes...
protected Sport Sport { get; set;}
}
public RealPlayer : Player
{
public void Foo(Sport sport)
{
this.Sport = sport; // Valid
}
}
In some other class...
var realPlayer = new RealPlayer();
realPlayer.Sport // Compilation error.
Upvotes: 5
Reputation: 1499800
Is this protected access modifier redudant since abstract cannot be instantiated?
No, absolutely not. Consider:
Player player = new FootballPlayer();
Sport sport = player.Sport;
That would be valid if Sport
were declared as a public property rather than protected. Of course, that may actually be what you want, but currently only code in derived classes (and within Player
itself) can access the Sport
property.
Note that your entire property would be simpler as an equivalent automatically implemented property though:
protected Sport Sport { get; set; }
Or to allow public getting but protected setting:
public Sport Sport { get; protected set; }
Upvotes: 9