Over riding static methods

hi i wrote two static methods with same signatures in two different classes. i know that static methods never override.but observe this code..
class staticoverload1
static void display()
               System.out.println("i am from first display");
class staticoverload2 extends staticoverload1
     static int a=10;
     static void display()
          staticoverload1.display();
          System.out.println("the value of x is:"+a);
class staticoverload
     public static void main(String args[])
          staticoverload2 s1=new staticoverload2();
          s1.display();
i got output as follows:
i am from first display
x value is :10
in the above problem over riding is happened or not

Please post your code in code tags.
s1.display();
Don't call static methods on objects. Tis ugly. But it will use the type of the reference.
class Test {
     public static void display() {
          System.out.println("Test");
     public static void main(String[] argv) {
          Test t = new Test2();
          t.display(); // Prints "Test". Even if you set it to null.
class Test2 extends Test {
     public static void display() {
          System.out.println("Test2");
}Finally this should have been posted in New To Java.

Similar Messages

  • Problem after over riding paintComponent() method

    I am over riding the paintComponent() method for a button to show the text in 2 lines. But when I invoke setEnabled(false) on the button, the button is getting disabled but the text is not.
    Could any one please let me know how to do that.
    The code for the paintComponent() method is pasted for reference
    protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    int w = getWidth();
    int h = getHeight();
    FontMetrics fm = g.getFontMetrics();
    int textw1 = fm.stringWidth(text1);
    int textw2 = fm.stringWidth(text2);
    FontRenderContext context = g2.getFontRenderContext();
    LineMetrics lm = getFont().getLineMetrics(text1, context);
    int texth = (int)lm.getHeight();
    prefHeight = texth;
    int x1 = (w - textw1) / 2;
    int x2 = (w - textw2) / 2;
    int th = (texth * 2);
    int dh = ((h - th) / 2);
    int y1 = dh + texth - 3;
    int y2 = y1 + texth;
    // Draw texts
    g.setColor(getForeground());
    g.drawString(text1, x1, y1);
    g.drawString(text2, x2, y2);
    regards,
    shantanu

    Hi,
    Thanks for advices, I solved the problem...it was simplier than i thought. When the g.drawImage(.... is called ) i just added Thread.sleep( time ) after that line. This gives the sound therad time to play the sound without interrput and time to main thread to handle the image. All works now pretty much as i thought, except when JFrame is overlapped the image is not drawn again...this can be corrected ( maybe?)by adding windoslistener and implement the methods in that inteface and make some repainting in different situations. But cause you gave me the magic work Thread priority I hox! the problem, so here goes 10 duke dollars.

  • Over riding hashtable get and put method

    Hi all
    Anyone have any idea about over ride HashTable get() and put(). Is it possible to over ride HashTable methods.

    Yes_me wrote:
    I want to change the structure of the java HashTable get and put method. As put method is having two object parameters I want to send one more parameter as String to it. Is it possible to change the structure in this way.What would you want to be returned when calling get()? I would go with the suggestion to create a class to keep that information. If you really want to, you can completely hide that information class inside your extended HashTable. You could create an overloaded put method that takes three parameters and then creates an instance of the information class and put that into the map. If you only want the data for display only, the get method could get the information class mapped to the given key, then simply return a nicely formatted String containing the two values.

  • Can you override a public static method?

    Can you override a public static method?

    A static method belongs to a class, not to a particular object, because you can call them without having an object instantiated. Methods are over rided which are inherited from an object. Since Static methods (although inherited) are not bound to a particular object, are not overridden.
    Though you have a method in the subclass with the same signatures but if you try to call super.____() you will get the error
    non-static variable super cannot be referenced from a static context

  • On static method override-

    just posted an example of over riding a static method . Is this legal? I mock cert exam is saying that static methods can not be overridden, What's the truth?

    As I know static method cannot override by non-static method and vice versa.

  • From Classic abap FMs to ObjectOriented instance/static methods: reference

    Hi All,
    we are migrating one of our project developed using classic abap to abap objects.
    mostly we are replacing the Function modules with either instance methods or static methods.
    for e.g.
    if there are FMs like GUI_UPLOAD, SO_NEW_DOCUMENT_SEND_API1 are used, after exploring in sdn for abap objects, we realized
    we can use cl_gui_frontend_services=>gui_upload( ) instead of the GUI_UPLOAD.
    send_request = cl_bcs=>create_persistent( ). send_request->send( ).  can be used instead of SO_NEW_DOCUMENT_SEND_API1
    like that there are several FMs present, is there any easy way where we can find this reference of object oriented methods corresponding to the plain old Function modules of classic abap.
    i was thinking, after seeing the blogs of people like Thomas Jung, Horst Keller, they encouraged a lot on abap objects over procedural abap. are there any such guidlines, references present to migrate (rather upgrade) to abap objects from existing procedural abap
    thanks,
    Madhu_1980

    I don't think it makes sense to do 1:1 mapping and replacement in your code.
    It does make sense to refactor using Object oriented techniques and patterns but it is usually a non-trivial task.

  • Static Methods with all Final Parameters

    Gurus,
    I know the synchronization and static method question has been hashed out ad infinitum here. However, I was thinking of a slight twist. (Did a search but could not find something related to this. If this has already been posted, my apologies).
    Suppose you have a static method in which all of the parameters in the method signature are declared final. Let's assume also that you are not performing an operation with a high latency (say, database or network operations).
    Would it be "safe" to leave the static method unsynchronized in a multi-threaded environment? Would the final keyword(s) ensure that, throughout method execution, there is no longer a race condition?
    Would there be a difference between a primitive:
    static final public void doSomething(final int param) {}
    And an object that has mutator methods:
    static final public void doSomething(final List param) {}
    Basically, not having a formal CS background, I'm not sure how static methods are actually invoked on a low-level. It probably varies across JVM's, and maybe this question doesn't make much sense. However, I thought I would throw this out to see if anyone had implemented something similar.
    I might be giving "final" too much credit., but what would actually happen in a multi-threaded environment?
    Thanks much!
    - Saish
    "My karma ran over your dogma." - Anon

    I know the synchronization and static method question
    has been hashed out ad infinitum here. What question's that then?
    Suppose you have a static method in which all of the
    parameters in the method signature are declared final.
    Let's assume also that you are not performing an
    operation with a high latency (say, database or
    network operations).
    Would it be "safe" to leave the static method
    unsynchronized in a multi-threaded environment?Whether or not the parameters are final makes no difference - method parameters are local to the method and so are only visible to the current thread anyway. So making them final will have no effect on anything goning on in any other thread.
    Whether or not you are performing operations has no effect on whether or not you can call a method thread-safe. It might mean there is less contention and it might make race conditions less likely, but it won't eliminate them.
    So the answer is: If your would be thread safe with non-final parameters, then it will still be thread-safe when the parameters are all final. If it is not thread-safe with non-final parameters, then it will still not be thread safe with final parameters.
    Would the final keyword(s) ensure that, throughout
    t method execution, there is no longer a race
    condition?No. Absoloutely not.

  • Static methods. Why?

    I understand what static means, and that each class has only ONE copy of its static variables and methods.
    I an see the benefits of using static variables, but i cant seem to get my head round the benefits of using static methods.
    What is the advantage of this, and is there a common situation where they are appropriate? (not main)
    Cheers

    I don't think static exists to prevent namespace conflicts. I think that the reason for static to exist is just as I described it: When you've got some task that is appropriate to be performed by a specific class, but that doesn't make sense to be associated with a particular instance of that class.
    For example, String.valueOf. It's appropriate for the String class to have a method that returns the String representation of anything you feed to it (so it's in the String class) but it doesn't make sense for that method to be associated with a particular instance of String (so it's static). After all, you don't yet have a String to operate on--you're producing the String.
    Which raises another interesting point: I wonder what the design decision was that led to
    String.valueOf(int)
    String.valueOf(long)
    String.valueOf(Object)
    etc.
    instead of
    new String(int)
    new String(long)
    newString(Object)
    etc.
    I've used both patterns in my own work, but I don't really have any good criteria for picking one over the other.
    One thing that comes to mind for the general case is that with the static method, you can return a subclass, which you can't do with a constructor. Conversely, with a constructor, the caller knows exactly which class he'll get, whereas with a static method he doesn't. Of course, these points don't apply to String, as it's final.
    I'm new to java, but as far as I can tell, "static"
    means "global". The reason for having them in classes
    is mainly to prevent name conflicts. For instance,
    you could have an Array object, and a List object, and
    both could have sort() methods, but they may be very
    different types of methods. By forcing sort() to be a
    member of a class, instead of a global identifier, you
    have Array.sort() and List.sort(), which is much
    safer.
    It seems that the java designers went to great lengths
    to make sure there are no namespace conflicts in the
    language. Maybe they even went a bit too far in this
    sometimes.

  • Why not to use static methods - with example

    Hi Everyone,
    I'd like to continue the below thread about "why not to use static methods"
    Why not to use static methods
    with a concrete example.
    In my small application I need to be able to send keystrokes. (java.awt.Robot class is used for this)
    I created the following class for these "operations" with static methods:
    public class KeyboardInput {
         private static Robot r;
         static {
              try {
                   r = new Robot();
              } catch (AWTException e) {
                   throw new RuntimeException(e + "Robot couldn't be initialized.");
         public static void wait(int millis){
              r.delay(millis);
         public static void copy() {
              r.keyPress(KeyEvent.VK_CONTROL);
              r.keyPress(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_CONTROL);
         public static void altTab() {
              r.keyPress(KeyEvent.VK_ALT);
              r.keyPress(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_ALT);
                   // more methods like  paste(), tab(), shiftTab(), rightArrow()
    }Do you thinks it is a good solution? How could it be improved? I've seen something about Singleton vs. static methods somewhere. Would it be better to use Singleton?
    Thanks for any comments in advance,
    lemonboston

    maheshguruswamy wrote:
    lemonboston wrote:
    maheshguruswamy wrote:
    I think a singleton might be a better approach for you. Just kill the public constructor and provide a getInstance method to provide lazy initialization.Thanks maheshguruswamy for advising on the steps to create a singleton from this class.
    Could you maybe advise also about why do you say that it would be better to use singleton? What's behind it? Thanks!In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. So a singleton should be enough.But that doesn't answer why he should prefer a singleton instead over a bunch of static methods. Functionally the two are almost identical. In both cases there's only one "thing" on which to call methods--either a single instance of the class, or the class itself.
    To answer the question, the main reason to use a Singleton over a classful of static methods is the same reason the drives a lot of non-static vs. static decisions: Polymorphism.
    If you use a Singleton (and and interface), you can do something like this:
    KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();And then whatever is calling KBI's public methods only has to know that it has an implementor of that interface, without caring which concrete class it is, and you can substitute whatever implementation is appropriate in a given context. If you don't need to do that, then the static method approach is probably sufficient.
    There are other reasons that may suggest a Singleton--serialization, persistence, use as a JavaBean pop to mind--but they're less common and less compelling in my experience.
    And finally, if this thing maintains any state between method calls, although you can handle that with static member variables, it's more in keeping with the OO paradigm to make them non-static fields of an instance of that class.

  • The purpose of static methods ....?

    In lay mans terms can anyone tell me WHY we have static methods ?

    In lay mans terms can anyone tell me WHY we have
    static methods ?Static methods become class level methods and are no longer confined within the objects of the class.
    Static methods typically provide information about the class as a whole, such as the number of created objects etcetera. Another use is as an object factory. Instead of doing new all over the program you have a static create method you call to get new objects of the class.

  • Memory, instance vs static methods?

    Well, have memory problems again.
    Question: what is more efficient: using one single instance of a class all over the place, or put static methods in this class, so no instance is needed. I'm guessing it doesn't make a lot of difference, but who knows, I could be wrong...

    Well, it appears that they don't affect runtime memory as long as the class is not needed. I guess the classloader will only load the class onto the heap from jar.
    The application start about 100 KB of memory is available (and that is about all of the heap). While creating more objects, memory usage increases drasticly. Definantly more than only the data stored in the classes, so it must also be loading the bytecode at that time.
    I still have some tricks up my sleeve, so I hope I can work it out...

  • Static method called from a null object reference

    Hello folks,
    Here´s the code:
    public class TestClass {
         public static void main(String[] args) {
              StaticNull _null_ = null;
              _null_.testNull();
    class StaticNull {
         public static void testNull() {
              System.out.println("testNull");
    }I know that a static method belongs to the class, so you don´t need an
    instantiated object of that class to call it. But in the code above, as
    I'm calling the testNull method from a null reference, shouldn't a NullPointerException
    be thrown?
    Best regards,
    Danniel

    sometimes wrote:
    yawmark wrote:
    Calling static methods from a reference variable should be considered a bad practice. Our coding standards prohibit it, and I suspect we're not the only ones.
    ~what are you trying to say? your coding standard encourages what tricks to invoke static methods? i mean other than using a 'reference variable'?I think you are misreading yawmark's comment. He was saying that invoking a static method using a reference variable -- as though the method weren't static:
    var.staticMethod();...is bad practice. His shop's coding standards prohibit it. And that's a common coding style standard. IDE's often warn you of that, right?
    edit: and judging by your reply #7, you and yawmark would bond over a few jars of cold beverages. You seem think with one mind.

  • How to execute a static method twice

    Hi all,
    In the attached code, as you can see I call the method at.sendRequestString(), twice from main() method.
    The first line in sendRequestString() method is Authenticator.setDefault(new MyAuthenticator());
    Authenticator is an abstract class and setDefault is a static method in that class.
    When I call sendRequestString() for the second time, Authenticator.setDefault(new MyAuthenticator()); is not executed. ie; Authenticator.setDefault gets executed once and only once.
    Does this happen because that Authenticator.setDefault is a static method and it will be executed only once?
    If yes, how can I make it work for the second time?
    Here is my simple Java code. The username and password given in the code are just sample ones.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Authenticator;
    import java.net.MalformedURLException;
    import java.net.PasswordAuthentication;
    import java.net.URL;
    public class GetAuthenticatedData
         public String address;
         static String username;
         static String password;
         public GetAuthenticatedData(String address){
              this.address = address;
         public String sendRequestString()
              Authenticator.setDefault(new MyAuthenticator());//BEING STATIC METHOD, SET DEFAULT CALLED ONLY ONCE
             String str = null;
             try {
                 URL url = new URL(address);
                 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                 while (( str = in.readLine()) != null) {
                      return str;
                 in.close();
             } catch (MalformedURLException e) {
                  System.out.println("e1"+e);
             } catch (IOException e) {
                  System.out.println("e2"+e);
             Authenticator.setDefault(null);
              return str;
         public static void main(String args[]){
              username = "username1";
              password = "password1";
              GetAuthenticatedData at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username1 and password1"+at.sendRequestString());
              username = "username2";
              password = "password2";
              at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username2 and password2 "+at.sendRequestString());
    class MyAuthenticator extends Authenticator {
         public MyAuthenticator(){
              getPasswordAuthentication();
              protected PasswordAuthentication getPasswordAuthentication() {
                   PasswordAuthentication auth = new PasswordAuthentication(GetAuthenticatedData.username, GetAuthenticatedData.password.toCharArray());
                 System.out.println("Username"+auth.getUserName());
                 System.out.println("Password"+new String(auth.getPassword()));
                   return auth;
    }Please help with an appropriate solution.
    Any help in this regard will be well appreciated with dukes.
    Anees

    Thanks for your valuable help Looce. But it still does not solve the problem.
    Here is how I used your code.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.Authenticator;
    import java.net.MalformedURLException;
    import java.net.PasswordAuthentication;
    import java.net.URL;
    public class GetAuthenticatedData
         public String address;
         static String username;
         static String password;
         public GetAuthenticatedData(String address){
              this.address = address;
         MyAuthenticator authenticator = new MyAuthenticator("username1","password1".toCharArray());
         public String sendRequestString(String user, String pass)
              authenticator.setUsername(user);
              authenticator.setPassword(pass.toCharArray());
              Authenticator.setDefault(authenticator);
             String str = null;
             try {
                 URL url = new URL(address);
                 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                 while (( str = in.readLine()) != null) {
                      return str;
                 in.close();
             } catch (MalformedURLException e) {
                  System.out.println("e1"+e);
             } catch (IOException e) {
                  System.out.println("e2"+e);
             Authenticator.setDefault(null);
              return str;
         public static void main(String args[]){
              username = "username1";
              password = "password1";
              GetAuthenticatedData at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username1 and password1"+at.sendRequestString("username1","password1"));
              username = "username2";
              password = "password2";
              at = new GetAuthenticatedData("https://" + username +":"+ password + "@www.mybooo.com/core/Dd002wW.php?data={action:'contacts',args:''}");
              System.out.println("value corresponding to username2 and password2 "+at.sendRequestString("password2","password2"));
    * This class implements an Authenticator whose username and password information can
    * change over time.
    * @author Cynthia G., Sun Java forums: http://forums.sun.com/thread.jspa?messageID=10504183
    class MyAuthenticator extends java.net.Authenticator {
      /** Stored user name. */
      private String username;
      /** Stored password. */
      private char[] password;
      /** Constructs an instance of MyAuthenticator with the given initial user name
       * and password. These may be modified with the setUsername and setPassword
       * methods.
      public MyAuthenticator(String username, char[] password) {
        this.username = username;
        this.password = password;
      public void setUsername(String username) { this.username = username; }
      public void setPassword(char[] password) { this.password = password; }
      protected java.net.PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }
    }

  • Does static methods need to be synchrnized ?

    Hi All,
    I have some class (static) methods in my program running on Server-A, which call a service running on Server-B over HTTP. My program is accessed by different client threads which pass values for my class method's parameters, and my class method will return the value that it got from the service returned by Server-B.
    In such scenarion, which of the following options is better, and if you have any other option that suits well to this situation, please suggest:
    option 1: synchronize the static methods.
    option 2: modfiy the class methods to instance methods.
    option 3: leave it as it is, there is no problem.
    thanks,
    darbha.

    It looks you have to synchronize the static method (option 1).
    Only one client thread may use the HTTP connection at a time.

  • Serializing a static method

    is it possible to serialize a static method?
    For example
    Class foobar implements serializable
    public static void foo(){};

    If you serialize an Object and send it over a network, I believe that the program/class that is unserializing it must otherwise know (be able to create) an Object of that type. So the static method would already be available. The only other way would be with reflection, but I'm not sure if that works on serialized objects.

Maybe you are looking for

  • No suitable driver found?

    Hey, I've been searching this forum for a problem like mine (and I've found a few that are "like" mine, but none that are exactly the same or that will solve my problem). First, any information that might be relevant (I really have no idea how much o

  • Where can I find Documentation for Oracle financial installation

    Hi Where can I find Documentation for Oracle financial installation as which all modules to be downloaded for linuk server etc here is what I have found =================================== Oracle9i Application Server, Version 1.0.2.2.2 CD Pack for Li

  • Attaching a file after signing the form

    Hi, On my form there are two signatures. On signing the first signature field all the fieds above it get locked. Then i have the attchments sections and below it is the second signature field. But if i sign the first signature field the attachment(im

  • How to create API

    hi plz let me know how to create API for user defined class

  • HTMLCSS cache problems

    I don't know if this is right place to ask question, but I have to start from somewhere. I have problems with modified report in HTMLCSS when it is called via forms. It appears that report shows "old" (I guess cached) version when it is called via fo