<p>I hit this problem all the time. Suppose I am making a command line interface (Java or C#, the problem is the same I think, I will show C# here).</p>

<ol>
<li>I define an interface ICommand</li>
<li>I create an abstract base class CommandBase which implements ICommand, to contain common code.</li>
<li>I create several implementation classes, each extending the base class (and by extension the interface).</li>
</ol>

<p>Now - suppose that the interface specifies that all commands implement the Name property and the Execute method...</p>

<p>For Name each of my instance classes must return a string that is the name of that command. That string ("HELP", "PRINT" etc) is static to the class concerned. What I would love to be able to do is define:</p>

<p>public abstract static const string Name;</p>

<p>However (sadly) you cannot define static members in an interface.</p>

<p>I have struggled with this issue for years now (pretty much any place I have a family of similar classes) and so will post my own 3 possible solutions below for your votes. However since none of them is ideal I am hoping someone will post a more elegant solution.</p>

<hr>

<p>UPDATE:</p>

<ol>
<li>I can't get the code formatting to work properly (Safari/Mac?). Apologies.</li>
<li><p>The example I am using is trivial. In real life there are sometimes dozens of implementing classes and several fields of this semi-static type (ie static to the implementing class).</p></li>
<li><p>I forgot to mention - ideally I want to be able to query this information statically:</p>

<p>string name = CommandHelp.Name;</p></li>
</ol>

<p>2 of my 3 proposed solutions require that the class be instantiated before you can find out this static information which is ugly.</p>

[{'answer_id': 66546, 'author': 'Ewan Makepeace', 'author_id': 9731, 'author_profile': 'https://Stackoverflow.com/users/9731', 'pm_score': 0, 'selected': False, 'text': '<p>[Suggested solution #1 of 3]</p>\n\n<ol>\n<li>Define an abstract property Name in the interface to force all implementing classes to implement the name property.</li>\n<li>(in c#) Add this property as abstract in the base class.</li>\n<li><p>In the implementations implement like this:</p>\n\n<pre><code>public string Name \n{\n  get {return COMMAND_NAME;}\n}\n</code></pre>\n\n<p>Where name is a constant defined in that class.</p>\n\n<p>Advantages:</p>\n\n<ul>\n<li>Name itself defined as a constant.</li>\n<li>Interface mandates the property be created.</li>\n</ul>\n\n<p>Disadvantages:</p>\n\n<ul>\n<li>Duplication (which I hate). The exact same property accessor code pasted into every one of my implementations. Why cant that go in the base class to avoid the clutter?</li>\n</ul></li>\n</ol>\n'}, {'answer_id': 66557, 'author': 'Thomas Danecker', 'author_id': 9632, 'author_profile': 'https://Stackoverflow.com/users/9632', 'pm_score': 2, 'selected': False, 'text': '<p>You may consider to use attributes instead of fields.</p>\n\n<pre><code>[Command("HELP")]\nclass HelpCommand : ICommand\n{\n}\n</code></pre>\n'}, {'answer_id': 66596, 'author': 'Bob Dizzle', 'author_id': 9581, 'author_profile': 'https://Stackoverflow.com/users/9581', 'pm_score': 0, 'selected': False, 'text': "<p>just add the name property to the base class and pass it ito the base class's constructor and have the constuctor from the derived class pass in it's command name</p>\n"}, {'answer_id': 66602, 'author': 'Marcio Aguiar', 'author_id': 4213, 'author_profile': 'https://Stackoverflow.com/users/4213', 'pm_score': 1, 'selected': False, 'text': '<pre><code>public interface ICommand {\n      String getName();\n}\n\npublic class RealCommand implements ICommand {\n     public String getName() {\n           return "name";\n     }\n}\n</code></pre>\n\n<p>Simple as that. Why bother having a static field?</p>\n\n<hr>\n\n<p>Obs.: Do not use a field in an abstract class that should be initiated in a subclass (like <a href="https://stackoverflow.com/questions/66505/how-to-handle-static-fields-that-vary-by-implementing-class#66681">David B</a> suggestion). What if someone extends the abstract class and forget to initiate the field? </p>\n'}, {'answer_id': 66611, 'author': 'Sunny Milenov', 'author_id': 8220, 'author_profile': 'https://Stackoverflow.com/users/8220', 'pm_score': 0, 'selected': False, 'text': '<p>What I usually do (in pseudo):</p>\n\n<pre><code>abstract class:\n\nprivate const string nameConstant = "ABSTRACT";\n\npublic string Name\n{\n   get {return this.GetName();}\n}\n\nprotected virtual string GetName()\n{\n   return MyAbstractClass.nameConstant;\n}\n\n----\n\nclass ChildClass : MyAbstractClass\n{\n   private const string nameConstant = "ChildClass";\n\n   protected override string GetName()\n   {\n      return ChildClass.nameConstant;\n   }\n}\n</code></pre>\n\n<p>Of course, if this is a library that other developers will use, it wouldn\'t hurt if you add some reflection in the property to verify that the current instance in fact does implement the override or throw an exception "Not Implemented".</p>\n'}, {'answer_id': 66618, 'author': 'Ewan Makepeace', 'author_id': 9731, 'author_profile': 'https://Stackoverflow.com/users/9731', 'pm_score': 0, 'selected': False, 'text': '<p>[Suggested solution #2 of 3]</p>\n\n<ul>\n<li>Make a private member variable name.</li>\n<li>Define an abstract property Name in the interface.</li>\n<li><p>Implement the property in the base class like this:</p>\n\n<pre><code>public string Name\n{ \n  get {return Name;}\n}\n</code></pre></li>\n<li><p>Force all implementations to pass name as a constructor argument when calling the abstract base class constructor:</p>\n\n<pre><code>public abstract class CommandBase(string commandName) : ICommand\n{\n  name = commandName;\n}\n</code></pre></li>\n<li><p>Now all my implementations set the name in the constructor:</p>\n\n<pre><code>public class CommandHelp : CommandBase(COMMAND_NAME) {}\n</code></pre></li>\n</ul>\n\n<p>Advantages:</p>\n\n<ul>\n<li>My accessor code is centralised in the base class. </li>\n<li>The name is defined as a constant</li>\n</ul>\n\n<p>Disadvantages</p>\n\n<ul>\n<li>Name is now an instance variable -\nevery instance of my Command classes\nmakes a new reference rather than\nsharing a static variable.</li>\n</ul>\n'}, {'answer_id': 66631, 'author': 'Staale', 'author_id': 3355, 'author_profile': 'https://Stackoverflow.com/users/3355', 'pm_score': 0, 'selected': False, 'text': '<p>My answer will relate to Java, as that is what I know. Interfaces describe behavior, and not implementation. Additionally, static fields are tied to the classes, and not instances. If you declared the following:</p>\n\n<pre><code>interface A { abstract static NAME }\nclass B { NAME = "HELP" }\nclass C { NAME = "PRINT" }\n</code></pre>\n\n<p>Then how could this code know which NAME to link to:</p>\n\n<pre><code>void test(A a) {\n    a.NAME;\n}\n</code></pre>\n\n<p>How I would suggest to implement this, is one of the following ways:</p>\n\n<ul>\n<li>Class name convention, and the base class derives the name from the class name. If you wish to deviate from this, override the interface directly.</li>\n<li>The base class has a constructor which takes name</li>\n<li>Use annotations and enforce their presence through the base class.</li>\n</ul>\n\n<p>However, a much better solution is proabably to use enums:</p>\n\n<pre><code>public enum Command {\n    HELP { execute() }, PRINT { execute() };\n    abstract void execute();\n}\n</code></pre>\n\n<p>This is much cleaner, and allows you to use switch statements, and the NAME will be easily derived. You are however not able to extended the number of options runtime, but from your scenario description that might not be even needed.</p>\n'}, {'answer_id': 66658, 'author': 'Ewan Makepeace', 'author_id': 9731, 'author_profile': 'https://Stackoverflow.com/users/9731', 'pm_score': 0, 'selected': False, 'text': '<p>[Suggested answer # 3 of 3]</p>\n\n<p>I have not tried this yet and it would not be so nice in Java (I think?) but I could just tag my classes with Attributes:</p>\n\n<p>[CammandAttribute(Name="HELP")]</p>\n\n<p>Then I can use reflection to get that static information. Would need some simple helper methods to make the information easily available to the clients of the class but this could go in the base class.</p>\n'}, {'answer_id': 66679, 'author': 'Jeromy Irvine', 'author_id': 8223, 'author_profile': 'https://Stackoverflow.com/users/8223', 'pm_score': 2, 'selected': False, 'text': '<p>As you mentioned, there is no way to enforce this from the interface level. Since you are using an abstract class, however, what you <em>can</em> do is declare the property as abstract in the base class which will force the inheriting class it override it. In C#, that would look like this:</p>\n\n<pre><code>public abstract class MyBaseClass\n{\n  public abstract string Name { get; protected set; }\n}\n\npublic class MyClass : MyBaseClass\n{\n  public override string Name\n  {\n    get { return "CommandName"; }\n    protected set { }\n  }\n}\n</code></pre>\n\n<p>(Note that the <em>protected set</em> prevents outside code changing the name.)</p>\n\n<p>This may not be exactly what you\'re looking for, but it\'s as close as I think you can get. By definition, static fields <em>do not</em> vary; you simply can\'t have a member that is both static and overridable for a given class.</p>\n'}, {'answer_id': 74982, 'author': 'Shire', 'author_id': 10253, 'author_profile': 'https://Stackoverflow.com/users/10253', 'pm_score': 0, 'selected': False, 'text': "<p>From a design perspective, I think it is wrong to require a static implementation member...  The relative deference between performance and memory usage between static and not for the example string is minimal.  That aside, I understand that in implementation the object in question could have a significantly larger foot print...</p>\n\n<p>The essential problem is that by trying to setup a model to support static implementation members that are avaialble at a base or interface level with C# is that our options are limited...  Only properties and methods are available at the interface level.</p>\n\n<p>The next design challenge is whether the code will be base or implementation specific.  With implementation your model will get some valdiation at compile time at the code of having to include similar logic in all implementations.  With base your valdiation will occur at run time but logic would be centralized in one place.  Unfortunately, the given example is the perfect show case for implemntation specific code as there is no logic associated with the data.</p>\n\n<p>So for sake of the example, lets assume there is some actual logic associated with the data and that it is extensive nad/or complex enough to provide a showcase for base classing.  Setting aside whether the base class logic uses any impelementation details or not, we have the problem of insuring implemtation static initialization.  I would recommend using an protected abstract in the base class to force all implementations to created the needed static data that would be valdated at compile time.  All IDE's I work with make this very quick any easy.  For Visual Studio it only takes a few mouse clicks and then just changing the return value essentially.</p>\n\n<p>Circling back to the very specific nature of the question and ignoring many of the other design problems...  If you really must keep this entire to the nature of static data and still enforce it thru the nature confines of the problem...  Definately go with a method over properties, as there are way to many side effects to make go use of properties.  Use a static member on the base class and use a static constructor on the implementations to set the name.  Now keep in mind that you have to valdiate the name at run-time and not compile time.  Basically the GetName method on the base class needs to handle what happens when an implementation does not set it's name.  It could throw an exception making it brutally apparent that something is worng with an implementation that was hopefulyl cause by testing/QA and not a user.  Or you could use reflection to get the implementation name and try to generate a name...  The problem with reflection is that it could effect sub classes and set up a code situation that would be difficult for a junior level developer to understand and maintain...</p>\n\n<p>For that matter you could always generate the name from the class name thru reflection...  Though in the long term this could be a nightmare to maintain...  It would however reduce the amount of code needed on the implementations, which seems more important than any other concerns.  Your could also use attributes here as well, but then you are adding code into the implementations that is equivalent in time/effort as a static constructor and still have the problem off what todo when the implementation does not include that information.</p>\n"}, {'answer_id': 227578, 'author': 'Hallgrim', 'author_id': 15454, 'author_profile': 'https://Stackoverflow.com/users/15454', 'pm_score': 0, 'selected': False, 'text': '<p>What about something like this:</p>\n\n<pre><code>abstract class Command {\n   abstract CommandInfo getInfo();\n}\n\nclass CommandInfo {\n  string Name;\n  string Description;\n  Foo Bar;\n}\n\nclass RunCommand {\n  static CommandInfo Info = new CommandInfo() { Name = "Run", Foo = new Foo(42)  };\n\n  override commandInfo getInfo() { return Info; }\n}\n</code></pre>\n\n<p>Now you can access the information statically:</p>\n\n<pre><code>RunCommand.Info.Name;\n</code></pre>\n\n<p>And from you base class:</p>\n\n<pre><code>getInfo().Name;\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/66505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9731/']