Subclass vs Wrapper - Constructor With An Addition

2019-08-03 03:49发布

问题:

Which is generally considered the more preferred method when trying to add a constructor with an additional parameter? A subclass or a wrapper? That being, creating a subclass of the class and then just using that subclass' constructor? Or adding a wrapper method which will take the extra parameter and return an object with that parameter set?

Thank you for your time!

EDIT:

I don't have access to the superclass's code.

回答1:

The answer is language dependent. In C#/.NET, you would typically use an overloaded constructor:

public class Foo 
{
   private readonly string _greeting;

   public Foo() : this("Hello") { }

   public Foo(string greeting) {
     _greeting = greeting;
   } 

   //...
}