Static Methods, the case of HashMap

    static int hash(Object x) {
        int h = x.hashCode();
        h += ~(h << 9);
        h ^=  (h >>> 14);
        h +=  (h << 4);
        h ^=  (h >>> 10);
        return h;I was cruising the HashMap class. And I noticed right away that all non interface methods were static package methods. Now isn't that bad OOP practice? Right. It breaks the inheritance relationship.
It means I cannot make a subclass of HashMap and re-write that hash function. Was that intentional?
on a OOP perspective or
on a down to earth matter,
Are static method more performant in speed? Or memory ( i guess yes here)? or what?

I was cruising the HashMap class. And I noticed right
away that all non interface methods were static
package methods. Now isn't that bad OOP practice?
Right. It breaks the inheritance relationship.
It means I cannot make a subclass of HashMap and
re-write that hash function. Was that intentional?If they are package-private, I take it for granted they didn't want application developers to redefine these methods.
If they are static, they are also preventing themselves (Javasoft) to override them in subclasses that would be included in the JDK.
I'd say in both cases, that it is intentional, since, at least in the case of the hash function, the intent is to disperse hash results even for low-dispersing custom hash functions, as was explained in another thread in ALT (wasn't it you already? ;-).
This is maybe questionable, but defendable, that they didn't want any subclass to mess with these "optimizations".
You can regard this as poor OO practice, but this is no more hampering you that if they had declared the method as private.
I acknowledge that declaring the method private has the advantage of making explicit that they don't want anyone to override it.
But by declaring it static package, they ensure no-one can override it, so the other methods in HashMap relying on this method are guaranteed that no subclass can mess with it, but other classes in the same package (say, WeakHashMap, HashSet,...), can call it. all the same
Are static method more performant in speed? Or memory
( i guess yes here)? or what?Static methods are not faster in themselves, but invoking them may be, since they can be "statically" resolved.
When the calling class is loaded in memory, the callee is loaded too, and the interpreter or JIT or HotSpot is free to inline the static method's body (no indirection).
Even if it doesn't, invoking the static method implies to moving the program counter or pointer, or whatever, to an adress that has already been resolved once and for all (one indirection),
whereas invoking a virtual method implies a double indirection, looking up the address in some kind of dynamic table (one per class, determined by the target object's leaf class).
There are indeed two different bytecodes for these two situations!

Similar Messages

  • Singleton or static methods for DAO?

    Which is the preferred way of creating a DAO which has no state...Singleton or static methods for DAO? and why? What are the issues implement one over the other?

    A [url http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html]DAO is an object that abstracts different data source access mechanisms by providing a common interface, decoupling the client code from the data layer implementation, and allowing differrent data sources to be used without changing the client code.
    This is not possible with static methods- you would have to change the client code to use a different data source.
    There is a similar pattern, the facade, where an object/utility class provides the interface to a set of functionality. In the case of a facade with static methods, the facade class needs to be rewritten to use a different implementation. This is possible, but means only one implementation may exist in each version of the software. A static method facade is a tighter coupled solution to a similar problem; tight coupling occasionally makes a measurable improvement in performance, but always reduces flexibility and requires destructive editing to change its implementation.
    Pete

  • How to get the class name  static method which exists in the parent class

    Hi,
    How to know the name of the class or reference to instance of the class with in the main/static method
    in the below example
    class AbstA
    public static void main(String[] args)
    System.out.println(getXXClass().getName());
    public class A extends AbstA
    public class B extends AbstA
    on compile all the class and run of
    java A
    should print A as the name
    java B
    should print B as the name
    Are there any suggestions to know the class name in the static method, which is in the parent class.
    Regards,
    Raja Nagendra Kumar

    Well, there's a hack you can use, but if you think you need it,Could you let me the hack solution for this..
    you probably have a design flaw and/or a misunderstanding about how to use Java.)May be, but my needs seems to be very genuine..of not repeat the main method contents in every inherited class..
    The need we have is this
    I have the test cases inheriting from common base class.
    When the main method of the test class is run, it is supposed to find all other test cases, which belong to same package and subpackages and create a entire suite and run the entire suite.
    In the above need of the logic we wrote in the main method could handle any class provided it knows what is the child class from which this main is called.
    I applicate your inputs on a better way to design without replicating the code..
    In my view getClass() should have been static as the instance it returns is one for all its instances of that class.
    I know there are complications the way compiler handles static vars and methods.. May be there is a need for OO principals to advance..
    Regards,
    Raja Nagendra Kumar
    Edited by: rajanag on Jul 26, 2009 6:03 PM

  • Help with writing a static method in my test case class inside blue j

    I have this method that I have to test. below is the method I need to test and what I have to create inside my test case file to test it Im having big time problems getting going. Any help is appreciated.
    public String introduceSurprise ( String first, String last ) {
    int d1 = dieOne.getFace();
    Die.roll();
    if (d1 %4 == 2){
    return Emcee.introduce(first);
    else {
    return this.introduceSpy (first,last);
    So how do write tests to verify that every fourth call really does give a randomized answer? Write a static method showTests which
    creates an EmCee,
    calls introduceSurprise three times (doing nothing with the result (!)),
    and then calls it a fourth time, printing the result to the console window.
    Write this code inside your test class TestEmCee, not inside EmCee!

    hammer wrote:
    So how do write tests to verify that every fourth call really does give a randomized answer? Write a static method showTests which
    creates an EmCee,
    calls introduceSurprise three times (doing nothing with the result (!)),
    and then calls it a fourth time, printing the result to the console window.
    Write this code inside your test class TestEmCee, not inside EmCee!Those instructions couldn't be anymore straightforward. Make a class called TestEmCee. Have it create an EmCee object. Call introduceSurprise on that object 3 times. Then print the results of calling it a 4th time.

  • Why is the static method in the superclass more specific?

    Why is the static method in the superclass more specific than the static method in the subclass? After all, int is a subtype of long, but Base is not a subtype of Sub.
    class Base {
        static void m(int i){ System.out.println("Base"); }
    class Sub extends Base {
        static void m(long l){ System.out.println("Sub"); }
    class Test {
        public static void main(String[] args) {
            int i = 10;
            Sub sub = new Sub();
            sub.m(i);
    }The first example compiles without error.
    Output: Base
    class Base {
        void m(int i){ System.out.println("Base"); }
    class Sub extends Base {
        void m(long l){ System.out.println("Sub"); }
    class Test {
        public static void main(String[] args) {
            int i = 10;
            Sub sub = new Sub();
            sub.m(i);
    }In the second example, both instance methods are applicable and accessible (JLS 15.12.2.1), but neither is more specific (JLS 12.2.2), so we get a compiler error as expected.
    : reference to m is ambiguous,
    both method m(int) in Base and method m(long) in Sub match
    sub.m(i);
    ^
    1 error
    Why don�t we get a compiler error for the static methods?

    Thank you for your ideas.
    ====
    OUNOS:
    I don't get Sylvia's response. This is about static methods, what are instances are needed for??Yes, the question is about static methods. I included the example with non-static methods for a comparison. According to JLS 15.12.2, both examples should cause a compiler error.
    And why you create a Sub object to call the method, and dont just call "Sub.m(..)"Yes, it would make more sense to call Sub.m(i). Let�s change it. Now, I ask the same question. Why is there no compiler error?
    ====
    DANPERKINS:
    The error in your logic stems from calling static methods on instances, as ounos pointed out. Solution: don't. You won't see any more ambiguities.A static member of a class may also be accessed via a reference to an object of that class. It is not an error. (The value of the reference can even be null.)
    Originally I was looking only at the case with non-static methods. Therefore, I used sub.m(i). Once I understood that case, I added the static modifiers. When posting my question, I wish I had also changed sub.m to Sub.m. Either way, according to JLS 15.12.2, a compiler error should occur due to ambiguous method invocation.
    ====
    SILVIAE:
    The question was not about finding an alternative approach that doesn't throw up an ambiguity. The question related to why, in the particular situations described, the ambiguity arises in only one of them.
    Yes.
    Proposing an alternative approach doesn't address the question.
    Yes.
    ====
    If anyone is really interested, here is some background to the question. Some people studying for a Sun Java certificate were investigating some subtleties of method invocations:
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=019182
    I remember seeing the non-static case discussed in this forum once before in a more practical context. jschell probably knows the link.

  • Why is it necessary to create an instance via the static method?

    Hi,
    For some classes (such as java.util.regex.Pattern), we should call the class method (static method) in order to create an instance (object).
    For example, in order to conduct the pattern matching, we should use the java.util.regex.Pattern class as follows:
    Pattern p = Pattern.compile ("X[0-9]+X") ;
      // An instance of the Pattern class is created.
    Matcher m = p.matcher ("abcX1XYX23Xz") ;
    while ( m.find() ){
      System.out.println ( m.start() ) ;
    }where the compile static method in the Pattern class creates an instance and returns the pointer (reference) of it. We should NOT call
    the constructor of the Pattern class as follows:
    Pattern p = new Pattern ("X[0-9]+X") ;    // ERRORThe question is the following:
    (1) In what scenes, do we develop the classes that force users to call the static method for creating an instance of it?
    (2) Why do the java.util.regex.Pattern class have such a specification?
    Thanks in advance.

    (1) In what scenes, do we develop the classes that force users to call the static method for creating an instance of it?1. As the other author mentioned, caching is one reason.
    2. With such caching, you don't need to take trouble in passing the reference of a cached object(s) to many places in your code. From anywhere in your code base, you can simply invoke the method, the object will come. In essence, the static method provides a global point of access to one or more pre-created (or cached) objects. Hence, the static method simplifies access to the object.
    3. Sometimes, the actual class instantiated is not the same as the one with the static method. This allows abstraction of underlying variations. For example, when you say Pattern.compile ("X[0-9]+X") , the returned object type can be different in Windows and Linux (Most probably Pattern class doesn't work like that, but I am showing you a use case. May be Runtime.getRuntime() does actually work like that.). You find this abstraction of variations in many places. Take for example, FacesContext.getExternalContext() method (this is from JSF API). ExternalContext documentation says this:
    "This class allows the Faces API to be unaware of the nature of its containing application environment. In particular, this class allows JavaServer Faces based appications to run in either a Servlet or a Portlet environment."
    Edited by: Kamal Wickramanayake on Oct 24, 2012 8:04 AM

  • 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

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • 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");
    }

  • 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();

  • Find the Class Name in a static method

    Hi All,
    I am trying to find the class name inside the static main method. I want to write one main method that loads an instance of the class. Other folks have suggested tricks with the security manager or creating an Exception to look at the stack trace, but these methods don�t reflect the inheritance. I want SUBCLASSES to be able to run from the command line using the inherited main method.
    public static void main(String args[]){
          JPanel thisJPanel = (JPanel) Class.forName(????).newInstance();
    }Any Ideas

    I want
    SUBCLASSES to be able to run from the command line
    using the inherited main method.Someone pointed this out already but more directly, static methods are not inherited.
    The behavior you desire ca be achieved using the Factory pattern.
    The idea of being able to subclass an application is a little bizarre. Why don't you just do something like this:
    public static void main(String[] args){
        // check that there is at least one parameter 
        JPanel thisJPanel = (JPanel) Class.forName(args[0]).newInstance();
    }

  • JNI static method call fails for the 6th time

    Hello,
    I have a JNI Method which calls the static method which gets reference to singleton class(getReference()), JVM crashes.
    what might be the problem?
    is it due to insufficient memory or any other reason?
    Here is my code.
    eScannerClass = gEnv->FindClass("com/elvista/jscaner/EScanner");
    eScannerContructId = gEnv->GetStaticMethodID(eScannerClass,"getReference","()Lcom/elvista/jscaner/EScanner;");
    eScannerUpdateMethodId = gEnv->GetMethodID(eScannerClass,"updateScanStatus","(Lcom/elvista/jscaner/EScanEvent;)V");
    eScannerObjectRef = gEnv->NewObject(eScannerClass,eScannerContructId);Thanx for any help on this.

    Hi,
    the eScannerContructId is refering a static method, not a constructor. Therefore you must not use gEnv->NewObject, which is only allowed for constructors. Instead you have to use gEnv->CallStaticObjectMethod to call getReference().
    Martin

  • Can we call a static method without mentioning the class name

    public class Stuff {
         public static final int MY_CONSTANT = 5;
         public static int doStuff(int x){ return (x++)*x;}
    import xcom.Stuff.*;
    import java.lang.System.out;
    class User {
       public static void main(String[] args){
       new User().go();
       void go(){out.println(doStuff(MY_CONSTANT));}
    }Will the above code compile?
    can be call a static method without mentioning the class name?

    Yes, why do it simply?
    pksingh79 wrote:
    call a static method without mentioning the class name?For a given value of   "without mentioning the class name".
        public static Object invokeStaticMethod(String className, String methodName, Object[] args) throws Exception {
            Class<?>[] types = new Class<?>[args.length];
            for(int i=0;i<args.length;++i) types[i] = args==null?Object.class:args[i].getClass();
    return Class.forName(className).getDeclaredMethod(methodName,types).invoke(null,args);

  • Which java keyword cannot be used inside the body of a static method?

    Which java keyword cannot be used inside the body of a static method, but may be used without problems in a non-static method?

    But javac doesn't complain. So I was not partially wrong -- I was completely wrong.It's still better not to use the "this", though. When you explictly reference a static member via an instance reference (theFoo.bar or this.bar, as opposed to Foo.bar) the JLS requires a check that the reference is non-null. Clearly "this" is always non-null, but javac still puts in half of the check. Take the simple class public class Test {
        static int field;
        public void setField(int i) {this.field=i;}
        public void staticSetField(int i) {field=i;}
    } and observe the bytecodes produced: $ javap -c Test
    Compiled from "Test.java"
    public class Test extends java.lang.Object{
    static int field;
    public Test();
      Code:
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   return
    public void setField(int);
      Code:
       0:   aload_0
       1:   pop
       2:   iload_1
       3:   putstatic       #2; //Field field:I
       6:   return
    public void staticSetField(int);
      Code:
       0:   iload_1
       1:   putstatic       #2; //Field field:I
       4:   return
    }The JIT will get rid of it, but you may as well avoid the waste in the first place. (And if you really do want to check that the reference is non-null, do the check explicitly so that maintainers know it's intentional).

  • What is the use of private static method/variable?

    Hi All,
    I have read lots of books and tried lots of things but still not very clear on the
    topic above.
    When exactly do we HAVE to use private static methods?
    private implies its only for class, cannot be accessed outside.
    But then static means, it can be accessed giving classname.method.
    They seem to be contradicting each other.
    Any examples explaining the exact behaviour will be well appreciated.
    Thanks,
    Chandra Mohan

    Static doesn't really "mean" that the method/field is intended for use outside the class - that is exactly what the access modifier is for.
    Static implies that it is for use in relation to the class itself, as opposed to an instance of the class.
    One good example of a private static method would be a utility method that is (only) invoked by other (possibly public) static methods; it is not required outside the class (indeed, it might be dangerous to expose the method) but it must be called from another static method so it, in turn, must be static.
    Hope this helps.

Maybe you are looking for

  • Header row in ALV Grid, based on the data in the table

    Hi All, I have a requirement wherein, based on the data in the table used for ALV, i need to add rows as sort of header in the ALV display. For e.g. my table has Appl No.  Item  Material  Desc.           Cost                 -> Column Heading 1      

  • Error in Generation of datasource

    Hi Experts, Ii have requirement variant configuration and same i need to develop in BI system. when i try to generate the datasource by using Tcode CTBW error is displaying BW meta data is incomplete. i Searched  prvious thread couldn't get a solutio

  • What do I do when my Ipad Mini says it is disabled?

    How do I reset my ipad so that the initial screen doesn't say ipad disabled???

  • Program  with a name starting with '!'

    Hi, I have a problem with a progam. In fact, I want to delete an include but this include is used in a program with a name starting with '!' like !ZMM_PR_TEST. I can't open this program or delete it. What can I do ? Must I delete this "strange" progr

  • Add-ons  with Add-on basic

    Hi, I'm about to develop an add-on for SAP business one and I would like to know whether the add-on will run if the user has an Add-on basic license. If so, is there anything I should know about it before creating the add-on?