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?
An Abstract class can have access modifiers like private, protected, and internal with class members. But abstract members cannot have a private access modifier. An Abstract class can have instance variables (like constants and fields). An abstract class can have constructors and destructors.
An abstract method can only set a visibility modifier, one of public or protected. That is, an abstract method cannot add static or final modifier to the declaration.
The Syntax for Abstract Class To declare an abstract class, we use the access modifier first, then the "abstract" keyword, and the class name shown below.
Normally the default access level of methods is package local.
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; }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With