开发者

Proper use of an abstract class

I am using .Net and have a simple master- and sub-class design. My master class contains nearly all the functionality and the sub-class only needs to set a value from the master. I was considering making the master an abstract class but there is no methods that I must override, but I'd like to reinforce the idea that the master class cannot necessarily exist on i开发者_如何学Gots own. Also, I'd like to reinforce that the property from the master must be set by the sub-class. What is appropriate here? Thanks for any help!


If nobody should ever create an instance of the master class, it is definitely appropriate to make it abstract.

As for the property, make it an abstract property. In the master, write something like:

public abstract int MyProperty { get; } 

and then the subclass must override it.


If the master class indeed cannot have concrete instances, then making it abstract is absolutely fine and indeed correct.


Abstract class is appropriate. You can have it have a protected constructor that takes the property you care about, so that sub-classes will have to supply that


My master class contains nearly all the functionality and the sub-class only needs to set a value from the master.

This sounds more like you should expose a static factory method in your master class that accepts this value and returns an instance of the master class. Make the constructor of the master class private so only your static factory method can create an instance of your master class.

Something like this:

public class MasterClass
{
    public string MyValue { get; set; }
    private MasterClass()
    {
    }

    public static MasterClass CreateMaster(string val)
    {
        MasterClass mc = new MasterClass() { MyValue = val };
        return mc;
    }
}


It should be fine to make the master class abstract - after all you never want it to be used without it being inherited.

You can also declare the property to be abstract, so that it will have to be overriden in the child class:

public abstract string MyProperty { get; set; }


If there is nothing to extend except for setting some specific state that is already in the "master" then it sounds like you don't need the inheritance at all and perhaps need instead to control how instances of your "master" class are constructed.

You could look at instead using a factory pattern.

However, if you are changing behaviour then definitely the use of abstract is warranted!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜