Bohn
Bohn

Reputation: 26919

Can an abstract class contain a public method?

Constructors of an abstract class shouldn't be public and they should be protected. My question is about methods in that abstract class. Can we declare them as public or they should be protected too for the same reason?

Upvotes: 3

Views: 9701

Answers (3)

Andy
Andy

Reputation: 8562

Abstract classes shouldn't have public constructors because they don't make sense. Abstract classes are incomplete, so allowing a public constructor (which anyone could call) wouldn't work as you can't instantiate an instance anyway.

Methods on abstract classes are another story. You can have implementation in an abstract class, which is the behavior that all subclasses will inherit. Think of a Shape class. Its purpose is to draw a shape on the screen, so it makes sense to make a Draw method public as you'll want callers to be able to ask your Shape to draw. The method itself can be abstract, forcing subclasses to implement, or possibly provide an implementation which may or may not allow overriding. It depends on what the defined behavior of your class should be.

Upvotes: 6

JaredPar
JaredPar

Reputation: 754763

The justification for constructors on abstract types being protected is that there is simply no other entity that could call the constructor other than a derived type. Making the constructor public is meaningless in this case as it can't ever be invoked outside the type hierarchy. Hence the recommendation is to use protected as it's the most appropriate access modifier.

The same logic doesn't hold true with other members on the type. They can be freely invoked from outside the type hierarchy should their access modifier permit it.

public abstract class Dog {

  // Public is appropriate here as any consumer of Dog could access
  // Breed on an instantiated object
  public abstract string Breed { get; }

  // Public would be meaningless here. It's not legal to say 
  // 'new Dog' because 'Dog' is abstract. You can only say 
  // 'new Poodle' or 'new Bulldog'.  Only derived types like
  // Poodle or Bulldog could invoke the Dog constructor hence it's
  // protected
  protected Dog() { }
}

public class Poodle : Dog { } 
public class Bulldog : Dog { }

Whether or not a particular member should be public or protected is highly dependent upon the particular API. The reasoning should be the exact same for abstract types as it is for non-abstract types

Upvotes: 10

Robert Harvey
Robert Harvey

Reputation: 180798

It depends on your use case. If you want the methods of the abstract class visible to instances of your derived class, you should make them public. If, on the other hand, you want the methods visible only to your derived class, you should make them protected.

Upvotes: 5

Related Questions