Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override a static method

I am extending a new class by inheriting from RolesService. In RolesService I have a static methog that I would like to override in my newly derived class. When I make the call from my derived object it does not use the overridden static method it actually calls the base class method. Any ideas?

public class RolesService : IRolesService {     public static bool IsUserInRole(string username, string rolename)     {         return Roles.IsUserInRole(username, rolename);     } }  public class MockRoleService : RolesService {     public new static bool IsUserInRole(string username, string rolename)     {         return true;     } } 
like image 856
Gabe Avatar asked Jan 15 '10 20:01

Gabe


People also ask

Can u override static method in Java?

Static methods are bonded at compile time using static binding. Therefore, we cannot override static methods in Java.

Can static methods be overloaded or overridden?

The static method is resolved at compile time cannot be overridden by a subclass. An instance method is resolved at runtime can be overridden. A static method can be overloaded.

Can we override static method in C?

No, they can't be overridden. They are associated with the class, not with an object. for the real use: you can call a static method without the class instance. Thanks.

Can you override a static or a private methods?

You cannot override a private or static method in Java. If you create a similar method with same return type and same method arguments in child class then it will hide the super class method; this is known as method hiding. Similarly, you cannot override a private method in sub class because it's not accessible there.


2 Answers

You can't override a static method. A static method can't be virtual, since it's not related to an instance of the class.

The "overriden" method in the derived class is actually a new method, unrelated to the one defined in the base class (hence the new keyword).

like image 99
Thomas Levesque Avatar answered Oct 05 '22 09:10

Thomas Levesque


Doing the following the will allow you to work around the static call. Where you want to use the code take an IRolesService via dependency injection then when you need MockRolesService you can pass that in.

public interface IRolesService {     bool IsUserInRole(string username, string rolename); }  public class RolesService : IRolesService {     public bool IsUserInRole(string username, string rolename)     {         return Roles.IsUserInRole(username, rolename);     } }  public class MockRoleService : IRolesService {     public bool IsUserInRole(string username, string rolename)     {         return true;     } } 
like image 24
mhinton Avatar answered Oct 05 '22 11:10

mhinton