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; } }
Static methods are bonded at compile time using static binding. Therefore, we cannot override static methods in Java.
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.
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.
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.
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).
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With