What is the difference between non-static method and static method of an abstract class?

我与影子孤独终老i 提交于 2019-12-01 06:56:42

Let me try to answer both of your questions -

I know it is not a best practice to use Static method in Abstract class, but what is the difference If I use both Static and non static method in abstract class

It is legitimate to have both static and non-static methods in your abstract class and yes, you are right in your beliefs that it is not a best practice to use Static method in Abstract class. When I conceptualize an abstract class, it should be intangible, simply abstract, like Shape. It is only when some class inherits an abstract class it gets life and make sense in real world like Circle or square. So yes you can use static and non-static methods just like with any other class, it would make little sense with abstract classes.

Is there any difference in calling these methods? When static method of an abstract will be invoked since we can't create object for an Abstract class.

You can call a non-static method on the instance of the class as usual, and yes you are right that we can't create object for an abstract class, static method will be called directly with class name like this, and it called as soon at compiler is executing the statement.

MyAbstractClass.StaticMethod();

You can use public static method of an abstract class as any other public static method. For example:

Logger.Configure();

You don't need instance of Logger to call Configure that way. And you can't call non-static methods of type without creating instance of that type. So, Logger.NonStaticMethod() won't work.

public or protected static methods can be called within class overload. You can't override them so they usually used as some kind of utility methods or as a non-overridable part of template method:

public class DerivedClass: AbstractClass
{
    public DerivedClass(Args args)
        : base(args)
    {
    }

    protected override void BuildResponses()
    {
        FormLoad(args);
    }
}

Also, public static methods sometimes used as factory methods:

public abstract class Logger
{
    public static Logger NLog()
    {
        return new NLogLogger();
    }
}

...

var logger = Logger.NLog();
logger.Log("Message");

You can see example of such usage in many places inside BCL: WebRequest.Create(...), for example, creates HttpWebRequest, FtpWebRequest and others which are derived from WebRequest.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!