Force Derived Class to Implement Static Method C#

So the situation is like, I have few classes, all of which have a standard CRUD methods but static. I want to create a base class which will be inherited so that it can force to implement this CRUD methods. But the problem is, the CRUD methods are static. So
I'm unable to create virtual methods with static (for obvious reasons). Is there anyway I can implement this without compromising on static.
Also, the signature of these CRUD methods are similar.
E.g. ClassA will have CRUD methods with these type of Signatures
public static List<ClassA> Get()
public static ClassA Get(int ID)
public static bool Insert(ClassA objA)
public static bool Update(int ID)
public static bool Delete(int ID)
ClassB will have CRUD signatures like
public static List<ClassB> Get()
public static ClassB Get(int ID)
public static bool Insert(ClassB objB)
public static bool Update(int ID)
public static bool Delete(int ID)
So I want to create a base class with exact similar signature, so that inherited derived methods will implement their own version.
For E.g. BaseClass will have CRUD methods like
public virtual static List<BaseClass> Get()
public virtual static BaseClassGet(int ID)
public virtual static bool Insert(BaseClass objBase)
public virtual static bool Update(int ID)
public virtual static bool Delete(int ID)
But the problem is I can't use virtual and static due to it's ovbious logic which will fail and have no meaning.
So is there any way out?
Also, I have few common variables (constants) which I want to declare in that base class so that I don't need to declare them on each derived class. That's why i can't go with interface also.
Anything that can be done with Abstract class?

Hi,
With static methods, this is absolutely useless.
Instead, you could use the "Singleton" pattern which restrict a class to have only one instance at a time.
To implement a class which has the singleton pattern principle, you make a sealed class with a private constructor, and the main instance which is to be accessed is a readonly static member.
For example :
sealed class Singleton
//Some methods
void Method1() { }
int Method2() { return 5; }
//The private constructor
private Singleton() { }
//And, most importantly, the only instance to be accessed
private static readonly _instance = new Singleton();
//The corresponding property for public access
public static Instance { get { return _instance; } }
And then you can access it this way :
Singleton.Instance.Method1();
Now, to have a "mold" for this, you could make an interface with the methods you want, and then implement it in a singleton class :
interface ICRUD<BaseClass>
List<BaseClass> GetList();
BaseClass Get(int ID);
bool Insert(BaseClass objB);
bool Update(int ID);
bool Delete(int ID);
And then an example of singleton class :
sealed class CRUDClassA : ICRUD<ClassA>
public List<ClassA> GetList()
//Make your own impl.
throw new NotImplementedException();
public ClassA Get(int ID)
//Make your own impl.
throw new NotImplementedException();
public bool Insert(ClassA objA)
//Make your own impl.
throw new NotImplementedException();
public bool Update(int ID)
//Make your own impl.
throw new NotImplementedException();
public bool Delete(int ID)
//Make your own impl.
throw new NotImplementedException();
private CRUDClassA() { }
private static readonly _instance = new CRUDClassA();
public static Instance { get { return _instance; } }
That should solve your problem, I think...
Philippe

Similar Messages

  • How to determine the Class of a static methods class?

    hi,
    is there a way to get the code below to output
    foo() called on One.class
    foo() called on Two.classthanks,
    asjf
    public class Two extends One {
       public static void main(String [] arg) {
          One.foo(); // should say "foo() called on One.class"
          Two.foo(); // should say "foo() called on Two.class"
    class One {
       public static final void foo() {
          System.out.println("foo() called on "/*+something.getClass()*/);
    }

    - One.class won't resolve to Two.class when the static
    method is called via the class TwoThat's because static methods are not polymorphic. They cannot be overridden. For example try this:
    public class Two extends One {
       public static void main(String [] arg) {
          One.foo(); // should say "foo() called on One.class"
          Two.foo(); // should say "foo() called on Two.class"
          One one = new Two();
          one.foo();
          ((Two) one).foo();
       public static void foo() {
          System.out.println("foo() called on Two");
    class One {
       public static void foo() {
          System.out.println("foo() called on One");
    }

  • Getting class in a static method

    I have a class with a static method. How can I return the class object with this method?
    public class Pencil {
    public static Class getClass() {
    Class class = ??? (this.getClass(), can�t use!)
    return class;
    Thanks!

    it would have to be like this:
    public static Class getClazz() {
    return Pencil.class;
    }

  • Derived class also implements interface?

    Hi guys,
    If a base class A implements an interface (e.g. Comparable), does a derived class of A also implement this interface (or is of this type e.g Comparable, if this is a more correct way to say it)??
    If so, would it be wrong to write "public class B extends A implements Comparable", because class A already implements it?
    I am aware of that class B will inherit methods from class B and that way have "compareTo()" method. But can objects of class B be plugged in for method parameter of Comparable ( someMethod(Comparable obj) )?

    LencoTB wrote:
    Hi guys,
    If a base class A implements an interface (e.g. Comparable), does a derived class of A also implement this interface (or is of this type e.g Comparable, if this is a more correct way to say it)??Yes. The way you said it is fine, although another way to say it is "Comparable is a base interface(or class) of derived class B"
    >
    >
    If so, would it be wrong to write "public class B extends A implements Comparable", because class A already implements it?Not necessarily, but it is unnecessary. The only reason you would do this is to specifically document that the class is changing the implementation of compareTo.
    >
    I am aware of that class B will inherit methods from class B and that way have "compareTo()" method. But can objects of class B be plugged in for method parameter of Comparable ( someMethod(Comparable obj) )?use "implements Comparable<B>"

  • How to get the current class name in static method?

    Hi,
    I'd like to get the current class name in a static method. This class is intended to be extended. So I would expect that the subclass need not to override this method and at the runtime, the method can get the subclass name.
    getClass() doesn't work, because it is not a static method.
    I would suggest Java to make getClass() static. It makes sense.
    But in the mean time, does anybody give an idea to work around it?
    Thank you,
    Bill

    Why not create an instance in a static method and use getClass() of the instance?
    public class Test {
       public static Class getClassName() {
          return new Test().getClass();

  • Abstract class and a static method

    Can i call a static method within an abstract class ?

    public class AbstractDemo {
      public static void main(String[] args) {
        BiPlane biPlane = new BiPlane();
        System.out.println("biplane propulsion = " + biPlane.getPropulsionType());
        JumboJet jumboJet = new JumboJet();
        System.out.println("jet load = " + jumboJet.confirmMaxLoad());
        System.out.println("jet speed = " + jumboJet.getTopSpeed());
        System.out.println(Airplane.confirmMaxLoad());
    abstract class Airplane {
      static String confirmMaxLoad() {
        return "go_get_um, yeehaa!";
      public abstract String getPropulsionType();
      abstract String getTopSpeed();
    class BiPlane extends Airplane {
      public BiPlane() {
        System.out.println("BiPlane constructor");
      static String confirmMaxLoad() {
        return "400 lbs";
      public String getPropulsionType() {
        return "propeller";
      final String getTopSpeed() {
        return "130 knots";
    class JumboJet extends Airplane {
      public JumboJet() {
        System.out.println("JumboJet constructor");
      public String getPropulsionType() {
        return "jet";
      public String getTopSpeed() {
        return "mach .87";
    }

  • Static methods in data access classes

    Are we getting any advantage by keeping functions of DAOs (to be accessed by Session Beans) static ?

    I prefer to have a class of static methods that
    require a Connection to do their work. Usually, there
    is a SessionBean that 'wraps' this DAO. The method
    signatures for the SSB are the same, minus the need
    for a Connection, which the SSB gets before delegating
    to the Static Class.Uggh, passing around a connection. I've had to refactor a bunch of code that used this pattern. We had classes in our system that took a class in their constructor simply because one of their methods created an object that needed the connection. Bad news--maintenance nightmare--highly inflexible.
    What we've done is create ConnectionFactory singletons that are used throughtout the application in order to get connections to the database. All connection factory implementations implement the same interface so they can be plugged in from other components at runtime.
    In my opinion, classes that use connections should manage them themselves to ensure proper cleanup and consistent state. By using a factory implementation, we simply provide the DAO classes the means by which they can retrieve connections to the database and even the name of the database that needs to be used that is pluggable. The DAO classes do their own connection management.
    For similar reasons, I eschew the static method concept. By using class methods, you make it difficult to plug in a new implementation at runtime. I much prefer the singleton pattern with an instance that implements a common interface instead of a class full of static methods.
    I recently needed to dynamically plug in new connection factory implementation so that we could use JNDI and DataSources within the context of the application server (pooled connections) but use direct connections via the Driver manager for unit testing (so the application server didn't need to be running). Because of the way this was coded, I simply changed the original factory to be an abstract factory and changed the getInstance() method to return a different implementation based on the environment (unit test vs live). This was painless and didn't require changing a single line of client code.
    If I had to do this using the previous code that I refactored, I would have had to change about 200 jsp pages and dozens of classes that were making calls to the static method of the previous factory or hacked in something ugly and hard to maintain.
    YMMV

  • Construct Derived Class in Static Block

    We've been having intermittent thread deadlock problems after migrating a stable system to Linux.
    One locked section we noticed occurred about 1 in 5 times, right at startup. The code looked fishy from the beginning, but I thought others could confirm whether it could be the cause of our problems.
    The code block constructs a derived class from a static block in the parent. Is it a recipe for failure? If so, why only intermittently and why not in Windows?

    The code block constructs a derived class from a
    static block in the parent.I don't understand that sentence. You have a block of code. It calls a constructor? It calls a constructor for a class that's derived from ... a static block? What do you mean?
    Is it a recipe for
    failure? If so, why only intermittently and why not
    in Windows?Intermittent failure is the nature of thread problems. Windows and Linux can have very different underlying implementations of threads.
    Show us some of the code and the failure mode.

  • Overloaded methods in a derived class

    Hello to everyone. I'm starting to learn java with the help of "Thinking in Java". I just want something to make it clearer for me.
    Suppose I have a base class with a method, and a derived class which overloads the method:
    class Base {
      void method() {
        System.out.println("Base method");
    class Derived extends Base {
      void method() {
        System.out.println("Derived method");
    }Now, in another class somewhere I create an instance of Derived:
    Derived dv = new Derived();
    dv.method();There is no way that I can access the method from the Base class, right? The only way I can do that is through
    class Derived extends Base {
      void method() {
        super();
        System.out.println("Derived method");
    }As I said, I'm almost sure that this is correct, I just want a confirmation.

    You can change the class
    class Derived extends Base {
      void method() {
        super.method();
        System.out.println("Derived method");
      // calls Base.method()
      void baseMethod() {
        super.method();
    }

  • What is the purpose of Static methods inside a class?

    Hi,
    What is the purpose of Static methods inside a class?
    I want the answers apart from "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    My question is what is the exact purpose of a static method ?
    Unlike attributes, a separate copy of instance attributes will be created for each instance of a class where as only one copy of static attributes will be created for all instances.
    Will a separate copy of instance method be created for each instance of a class and only one copy of static methods be create?
    Points will be rewarded for all helpful answers.

    Hi Sharma,
    Static methods is used to access statics attributes of a class. We use static attributes when we want to share the same attribute with all instances of a class, in this case if you chage this attribute through the instance A this change will change will be reflected in instance B, C........etc.
    I think that your question is correct -> a separate copy of instance method will be created for each instance of a class and only one copy of static methods be create ?
    "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    Static Method: call method class=>method.
    Instance Method: call method instance->method.
    Take a look at this wiki pages.
    [https://wiki.sdn.sap.com/wiki/x/o5k]
    [https://wiki.sdn.sap.com/wiki/x/ZtM]
    Best regards.
    Marcelo Ramos

  • Why java does not force to declare atleast one abstract method

    hi,
    i can define an abstract class without declaring any abstract method in that class. But why wud i do this ? i mean when i have decided that a particular class should be inherited by other subclass and subclass should porvide implementation then there should be atleast one method in the abstract super class which requires implementation.
    All i want to know is why java does not force to declare atleast one abstract method in abstract class.
    there may be some situations where this restriction can create problem if it is like that then can anybody give some example.
    manish

    hi,
    i didn't get u.
    u r trying to say that i have an abstract class with
    only static methods then my questions is why wud
    declare such a class as 'abstract' class? because a
    static method can't be abstract also. Even then if
    somebody want to define such a class with only static
    methods then compiler should force him to declare
    atleast one abstract method which can be implemented
    by subclass, because as i said before if sumbody
    decide to define a class abstract then he wants that
    it should be inhereted but as u r saying a class with
    only static methods then it should not be an abstract
    class it can be a simple class.there's no functional reason, really... actually, factory-like classes are often defined the way Ceci described
    "abstract" only ensures that nobody can ever get an instance of that class (as a matter of fact, what would be the point of getting an instance, if no instance method exists ?)

  • Dynamic call of a static method of an static attribute

    Hi all,
    is it possible to call dynamically a static method of a static attribute of a class.
    The statement without dynamic call would look like this:
    cl_test_class=>static_attribute=>static_method( ).
    I would like to do it like this:
    ('CL_TEST_CLASS')=>static_attribute=>static_method( ).
    Netiher the one nor the other way works for me - I'm getting the error "The notation used is reserved for business object classes".
    Regards, Stefan

    I guess, it is not possible to call method using the short form (parameters in brackets) is not possible in Dynamic Access. You may need to get the attribute first and then call the method.
    CLASS lcl_main DEFINITION.
      PUBLIC SECTION.
        CLASS-DATA: o_same TYPE REF TO lcl_main.
        METHODS: run.
    ENDCLASS.                    "lcl_main DEFINITION
    CLASS lcl_main IMPLEMENTATION.
      METHOD run.
        WRITE: 'success'.
      ENDMETHOD.                    "run
    ENDCLASS.                    "lcl_main IMPLEMENTATION
    START-OF-SELECTION.
      DATA: lo_same TYPE REF TO lcl_main.
      CREATE OBJECT lcl_main=>o_same.
    *  lcl_main=>o_same=>run( ).
      TRY.
          FIELD-SYMBOLS: <fs> TYPE REF TO lcl_main.
          ASSIGN ('LCL_MAIN')=>('O_SAME') TO <fs>.
          CALL METHOD <fs>->('RUN').
        CATCH cx_root.
      ENDTRY.
    Regards,
    Naimesh Patel

  • Static methods vs instant methods

    hi to all abap gurus
    thanks in advance
    all of the objects in the class can acess its its static attributes . and if u change the static attribute in an  object the change is visible in all other objects in the calsssss.
    can u pls expain this and tell the diffrence bewteen static and instance metod s?

    Hi,
    <b>Instance Method</b>
    You can declare instance methods by using the METHODS statement. They play a very important role as they can access all of the attributes of a class and can trigger all of the events of the class.
    <b>Static Methods</b>
    You can declare static methods by using the CLASS-METHODS statement. They are important and can only access static attributes and trigger static events.
    <b>STATIC METHODS</b>
    CAN ONLY USE STATIC COMPONENTS IN THEIR IMPLEMENTATION PART
    CAN BE CALLED USING THE CLASS
    Static methods (also referred to as class methods) are called using CALL METHOD <classname>=><class_method>.
    If you are calling a static method from within the class, you can omit the class name.
    You access static attributes using <classname>=><class_attribute>
    Regards,
    Padmam.

  • Drawbacks of static methods?

    What's the better approach for utility methods:
    a) write abstract class with static methods
    b) write class with non-static methods and instantiate this class to call the public methods.
    ?

    What's the better approach for utility methods:Define "utility methods".
    a) write abstract class with static methodsProbably not - surely a final class would be better than an abstract one?
    b) write class with non-static methods and instantiate
    this class to call the public methods.Do you (or might you ever) want to be able to plug in different implementations? If so, then this is the better option. If not, then a final class with all methods static will probably do the job very well.

  • Static Vs Non-static methods

    Hello,
    I wonder what should I use. I have got a class which does a lot of counting.. I can put the methods inside the class or make a class Math3D with the static methods that will count it.
    Which is the better way?

    BigDaddyLoveHandles wrote:
    deepak_1your.com wrote:
    Sorry mate... did not get that.By definition a utility class has all static methods. So as soon as you mention "utility class" you've already made a decision. The real question is "should method X be static or non-static"? My default position is to assume no method should be static, and then wait to be convinced.
    Look at utility class java.lang.Math, for example. It has static methods sin(), cos(), sqrt(), etc... An obvious choice for a utility class, right? Then they introduced class StrictMath in 1.3 with exactly the same static method signatures. That's a code smell that one should have written an interface and implemented it in at least two ways, but it's too late for that because the original methods are static.Good post.

Maybe you are looking for

  • Payment against a check number

    Dear All, Im wondering whether i can post an outgoing payment and choose from a list the number of the check i want to make the payment against (from my check lot on the system).  Regards, Roba Motaweh Edited by: Roba Motaweh on Feb 22, 2011 3:11 PM

  • Express 8 on a G5 Dual 2.0,  7 gigs Ram, TIger

    I'm considering purchasing Express 8 to use on my G5..dual 2.0, 7 gigs RAM in Tiger 10.4.11. Currently using an Alesis io 14 interface without any problems into Cubase LE 4 Was wondering if anyone can provide some input as to performance issues? I've

  • Can I live without asmlib in Linux ?

    Platform : RHEL 5(64 bit) Grid Version: 11.2.0.3 I have only worked in Solaris and AIX before. I've done several RAC installations in Solaris/AIX. Our company has decided to move some of our RAC implementations to Linux because of the costs. From goo

  • Google Voice Search/Vlingo

    Hello, This app was fantastic - very easy to speak in search terms and look it up!  Worked great on the N95! But none for the N8!!!! Vlingo still has not N8 client. Any voice commands apps for the N8?  Is one built in? Help? Thanks, VeePee Nokia 3395

  • Pre-Install Warning

    I had file vault enabled on my macbook prior to installing Leopard due to work related sensitive material I had stored. Little did I know, file vault needs to be disabled before installing Leopard, otherwise you're going to run into some serious prob