Preview Knowledge Pack  devAdvantage

Abstract Types Should Not Have Public Constructors

Abstract types cannot be instantiated and should by design not have a public constructor.

By design abstract classes are used to provide an empty or partial implementation of a type and meant for subclasses to implement the remaining functionality.  They can never be implemented.  Therefore the recommended design pattern for doing this is to never create public constructors for your abstract class.  You should create protected constructors or supporting methods that can be used by the implementing constructor and require the implementer to expose the public constructor.  By designing this way you make the implementers of your class pay more attention to implementing the class.

 This rule violation can be automatically corrected with devAdvantage.

Example using public constructor (incorrect code)

[C#]
	// Abstract class definition
	public abstract class Shape
	{
		public Shape()
		{
		}
		abstract public double Area();
		abstract public double Circumference();
	}

	// Concrete class definition
	public class Square : Shape
	{
		private double x, y;
		public Square( double x, double y )
		{
			this.x = x;
			this.y = y;
		}
		public override double Area() {return x*y;}
		public override double Circumference(){return 2*(x+y);}
	}
		

Example using a protected constructor (correct code)

Note that this forces the implementer to be explicit in their constructor.
[C#]
	// Abstract class definition
	public abstract class Shape
	{
		protected Shape()
		{
		}
		abstract public double Area();
		abstract public double Circumference();
	}

	// Concrete class definition
	public class Square : Shape
	{
		private double x, y;
		public Square( double x, double y )
		{
			this.x = x;
			this.y = y;
		}
		public override double Area() {return x*y;}
		public override double Circumference(){return 2*(x+y);}
	}

See Also