Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access modifier on abstract classes

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?

like image 469
user1765862 Avatar asked Nov 26 '12 17:11

user1765862


People also ask

Can abstract class have access modifiers?

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.

Which access modifier is not allowed with abstract method?

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.

Which access specifier is used for abstract class?

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.

What is the default access modifier for the abstract method?

Normally the default access level of methods is package local.


2 Answers

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; }
like image 139
Jon Skeet Avatar answered Sep 29 '22 02:09

Jon Skeet


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.
like image 45
gdoron is supporting Monica Avatar answered Sep 29 '22 01:09

gdoron is supporting Monica