Can Static Methods be overridden ?

My question is can static methods be overridden ?
I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
According to that thread discussion, Java language states that static methods cannot be overridden.
To which kajbj posted a program which did allow overriding of static methods.To quote him :
I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
/Kaj This is one small program code which i wrote ,which did not allow static methods to be overridden,but no error as such was displayed.
package fundamentals;
class SuperClass
  public static String getName()
       return "HI,CLASS...SUPER CLASS";
  public int getAge()
       return 20;
} // END OF SUPER CLASS
public class SubClass extends SuperClass{
public static void main(String[] args)
          SubClass objSubClass=new SubClass();
          SuperClass objSuperClass=new SubClass();
          System.out.println(objSubClass.getName());      // SUB CLASS
          System.out.println(objSuperClass.getName());   // SUPER CLASS
          System.out.println(objSubClass.getAge());        // SUB CLASS
          System.out.println(objSuperClass.getAge());     // SUPER CLASS
                 public    static String getName()
                   return "HI,CLASS...SUB CLASS";
                 public int getAge()
                    return 40;
} // END OF MAIN CLASSWhich gives the O/P :
HI,CLASS...SUB CLASS
HI,CLASS...SUPER CLASS
40
40So,the static method was not overridden.
But ,why was no error message displayed ?
Also when i modify the subclass static method,by removing the static keyword as follows :
public  String getName()
                   return "HI,CLASS...SUB CLASS";
                 }A Error Message as :
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
     This instance method cannot override the static method from SuperClassis displayed.
Why this message is displayed after i remove the static keyword ?
So can we say that Java does not allow static method to be overridden but does not display a compile/run time error when this is done ?
Is this a bug as stated by kajbj ?
Please let me know if i am not clear.If this question has been answered somewhere else in this forum,kindly let me know.
Thank you for your consideration.

amtidumpti wrote:
My question is can static methods be overridden ?
I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
According to that thread discussion, Java language states that static methods cannot be overridden.
To which kajbj posted a program which did allow overriding of static methods.To quote him :
I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
/Kaj
Sigh! Amti, are you being misleading on purpose? Kaj did not "post a program which did allow overriding of static methods." He posted a program which used the annotation @Override on a static method, like this:
class A {
    public static void m() {}
class B extends A {
    @Override public static void m() {}
}He wondered why it didn't generate an error message. Well, it does now:
A.java:6: method does not override or implement a method from a supertype
    @Override public static void m() {}
    ^
1 error

Similar Messages

  • Can static methods overridden

    help me to know that static methods can be overridden with example

    No u can not override static,private or final methodsIt would be interesting for the OP to know why (the reason is very different in each of the three cases).
    @OP: the same question was posted a fey days ago and I posted there a reply, if you do a search in the forum you'll find it.

  • Can abstract method be overridden

    "An abstract method can be overridden by an abstract method"
    If an abstract method does not have any implementation, then what does one mean by overriding an abstract class in the subclass. Any code to show this will be of better understanding.
    Thanks..

    As yawmark demonstrated it can be use to to increase visibilty but it can also be used to reduce exception declarations.
    Example:
    abstract class A
        abstract void f() throws java.io.IOException, java.sql.SQLException;
    abstract class B extends A
        abstract void f() throws java.net.SocketException;   
    }

  • How are static methods handled in a multithreaded application?

    hi
    i have a class Drawer with a static method public static draw(Graphics g). now assume there are more thrads callin at the same time Drawer.draw(g). What happens? have some threads to wait until the others have finished calling the method, or can static methods be multithreaded, (can they perform simultaniously)?
    thanks, jo

    ups, i am not drawing on the screen, but in every thread i am drawing a Image. this means before i call the static method in every thread there will be created a BufferedImage and then i pass the Graphics from this images to the static method. also in this case the method performs simultaniously? every thread has its own image and graphics, so the static method should be perform at the same time, isn't it?

  • About static method

    can static methods be overloaded
    can static methods do not have access tp implicit variable calles this

    No overloading concept for static members.
    Try this:
    public class testest extends test2 {
    public static void out() {
    System.out.println (" hello world from testtest ");
    public static void main(String s[]) {
    test2 x = new testest();
    x.out();
    class test2 {
    public static void out() {
    System.out.println (" hello world from test2 ");
    c:\>javac testest.java
    c:\>java testest
    It will give you: hello world from test2.
    The point is: static members are not attached to instance, but to class itself
    So if you do this:
    test2 x = null;
    x.out();
    1. do you think it will compile?
    YES
    2. so what is the result?
    Same, hello world from test2
    3. Why?
    Because you declare x as test2.
    What JVM do is, it will see what class is x, it will find out that x is class of "test2". Then it will execute: test2.out()
    rgds,
    Alex

  • OOPs Concept ! - Why Static Methods can't be redefined in its subclass ?

    Dear Experts ,
    I had searched the SDN , but unable to find out the satisfactorily answers ..
    Can anybody let me know the reason for the following Confusion in Oops Concept
    Question 1: As we know , We can Inherit the Static Methods in the Sub Class , But we can't redefine it in the base class  or       Sub Class  ?
    Question 2 : Why can't Static Method be Abstract ?
    Question 3 : Can a Class be Abstract or Final Both, If yes, then why ?
    Thanks in Advance
    Saurabh Goel

    As per the above discussion two of your doubts have already been clarified  so I am taking only third one.
    A class cannot never be Abstract and final both coz Abstract signifies that the implementation of the class has not been defined completelyi.e. may be some methods have been defined but few methods are still missing implementation. 'Final' is used for those classes/methods which cannot be redefined  means the complete implementation of the method has been defined no one can implement further logic under the same method.
    If you are saying your method is Final then it cannot be overridden and Abstract implies that method implementation is yet to be defined which can only be implemented if that class/method is not 'Final'. So both the terms are contradictory.
    Hope it clarifies!!!
    Thanks,
    Vishesh

  • 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

  • Can you set a global EntityResolver (via system property, or static method)

    I'm trying to set a customized EntityResolver (telling the xml parser where to look for XML schema files).
    Usually, you'd use the standard syntax - somehting like:
    SaxParser parser=new SaxParser();
    parser.parser.setEntityResolver(myResolver);
    However, I was wondering whether you can set a "global" EntityResolver, to be used as default for all parsers ?
    Maybe this can be done through some system property, or a static method somewhere in the parsing XML ?
    (BTW, I need it because I'm using some third-party API, that encapsulates a SaxParser, but won't let me access it, so I can't configure it directly).
    thanks.

    I don't think you can.
    What is possible is to set content on the folder resource itself; that would be returned instead of the page you mentioned.

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

  • Static methods inside class in jsp can't make it work

    Hello all i can't understand it why i can't declare the method as static method ?
    public class Request{
              Request(){}
              private String paramValue;
              public static String getRequestParam(HttpServletRequest request, String paramName, String defaultValue){
                   paramValue = request.getParameter(paramName);
                   return paramValue != null ? paramValue : defaultValue;
    im geting this error :
    The method getRequestParam cannot be declared static; static methods can only be declared in a static or top level type
    can't i do inner class ?
    or other sulotion for me not to make instences of class's but to use the class static methods?

    Hi, try this:
    public class Request{
              Request(){}
              private static  String paramValue;
              public static String getRequestParam(HttpServletRequest request, String paramName, String defaultValue){
                   paramValue = request.getParameter(paramName);
                   return paramValue != null ? paramValue : defaultValue;
          }it should work. the problem in you code is that you are trying to referance an non-static object with a static one!
    Message was edited by:
    Adelx

  • Can only see 4 static methods out of 14

    I have a single public class containing about 14 public static methods and some inner clasess.
    When using the JDeveloper Ver3.1 build 681, to deploy these java methods as RDBMS stored procs, only 4 of the methods & inner classes are visible to publish.
    The methods available to publish are main(), another method which calls most of the other non-available methods and 2 completely independent methods.
    I need a clarification on my understaning.
    If a method A calls another method B in the same class but B is not published as a stored proc.
    When I invoke A, RDBMS sees a java source stored procedure and JSERVER kicks in. I presume that JSERVER can see all the methods declared in the class as I see in the *.java file.
    When you deploy, what is taken across from the *.java file apart from connection properties details.
    Any help/pointers will be appreciated. Thanx in advance.

    I have a single public class containing about 14 public static methods and some inner clasess.
    When using the JDeveloper Ver3.1 build 681, to deploy these java methods as RDBMS stored procs, only 4 of the methods & inner classes are visible to publish.
    The methods available to publish are main(), another method which calls most of the other non-available methods and 2 completely independent methods.
    I need a clarification on my understaning.
    If a method A calls another method B in the same class but B is not published as a stored proc.
    When I invoke A, RDBMS sees a java source stored procedure and JSERVER kicks in. I presume that JSERVER can see all the methods declared in the class as I see in the *.java file.
    When you deploy, what is taken across from the *.java file apart from connection properties details.
    Any help/pointers will be appreciated. Thanx in advance.

  • Can we override Static methods?

    Hi all, I m in little bit confusion abt static methods overriding.
    Could you help me on this issue.,
    Can we override Static methods?

    You can provide static methods with same name in both super class and subclass. But it is not overriding in this scenario. Both will act as independent methods.
    Example:
    have a super class:
    public class Test1 {
    public static void mthdA()
    System.out.println("in super");
    have a sub class:
    public class Test2 extends Test1{
    public static void mthdA()
    System.out.println("inside sub");
    public static void main(String[] args){
    Test1 objTest = new Test2();
    objTest.mthdA();
    Try to run the sub class Test2. The output would be "in super".
    Remove static modifier in mthdA() in both the classes and then run. The output would be "in sub". Meaning, methdA is overriden in sub class.

  • Can I have a static method?

    I want to know whether we can have static method and static block in Ejb.
    also I want to know the use of these and when these will be invoked by the container

    Technically speaking you can have static methods or static blocks the java compiler or teh ejb deployer will not complain
    However its always a good practice to avoid having static blocks, static methods in EJB
    if you have the urge to initialise or have a startup code in your application when EJB is loaded , you can implement the code in ejbCreate()
    - I dont see any other reason where you might need static block
    if there is any other reason please explain what cirumstances drives you to have static {} static mthd()
    if it is statess session Bean avoid having even non-static member variables
    Reasons for not having non-static member variable in Stateless Session EJB is
    1. stateless EJBs are pooled so the instances are pooled after use.. so there is a chance you might get the same instance with previous assigned values
    Hope the info helps!

  • Why interfaces can not declare static methods?

    Why interfaces can not declare static methods?

    Why are you shouting?
    Is your internet broken?
    [http://www.google.co.uk/search?q=interface+static+methods+java] 2,440,000 hits.

  • Can't get ClassLoader from static method.

    I'm trying to get the ClassLoader within a static method getInstance().
    public class PropertyManager {
    public static PropertyManager getInstance(String fileName) {
    //The following line returns null
    ClassLoader cl = (new Object()).getClass().getClassLoader();
    URL url = cl.getResource(fileName);
    etc...
    However if getInstance gets called from e.g. a statless session bean, a null
    is returned instead of a valid ClassLoader.
    The same code executed from a standalone java program (e.g. from
    main(String[] args)) returns a valid ClassLoader
    Why does getClassLoader behave differently in WebLogic than in a standalone
    java program?
    Thanks for you help.
    Bernie

    Sorry for the confusion. I wrote a couple of more test programs and was able
    to confirm that WL behaves exacltly the same as java does. For some reason
    my intial tests were messed up...
    getClassLoader() executed from a static method always returns null (in WL as
    well as in a java standalone program).
    In this case ClassLoader.getSystemClassLoader() will return a valid class
    loader.
    Thanks for your help.
    Bernie
    "Rob Woollen" <[email protected]> wrote in message
    news:[email protected]..
    Bernhard Lenz wrote:
    I tried that as well, but getClassLoader() still returns null when
    executed
    in WL.
    I'm still not clear how getClassLoader() gets affected by running withinWL.
    >>
    >
    Very odd. Where is this class located? in the server's classpath, in ajar or
    war file? Does getClass().getClassLoader work from a non-static method inthis
    class?
    -- Rob
    "Rob Woollen" <[email protected]> wrote in message
    news:[email protected]..
    You want PropertyManager.class.getClassLoader()
    -- Rob
    Bernhard Lenz wrote:
    I'm trying to get the ClassLoader within a static method
    getInstance().
    >>>>
    public class PropertyManager {
    public static PropertyManager getInstance(String fileName) {
    //The following line returns null
    ClassLoader cl = (new Object()).getClass().getClassLoader();
    URL url = cl.getResource(fileName);
    etc...
    However if getInstance gets called from e.g. a statless sessionbean, a
    null
    is returned instead of a valid ClassLoader.
    The same code executed from a standalone java program (e.g. from
    main(String[] args)) returns a valid ClassLoader
    Why does getClassLoader behave differently in WebLogic than in astandalone
    java program?
    Thanks for you help.
    Bernie

Maybe you are looking for

  • PHOTOSHOP CS5 ADJUSTMENT PRESET? *Expert*

    Im currently working on wedding photos right now, and i have a nice color theme to go by. Is there a way i can set a whole preset or apply these settings to a batch of photos instead of making changes one by one? (settings I'm doing below) *activate

  • Flash text in DW MX

    My site (redirect from www.johnbowlby.com) home page uses a lot of DW flash text elements with links to other pages on the site. Lately, a white box outline appears around any of the Flash text elements on the page. User has to click once to get the

  • Adding to My Podcasts not found

    How do you add podcasts to the My Podcasts app that are not found? Is there a way to use URL?

  • How to address seesion attribute with JSTL?

    Hi there, In login, I have set session attribute of userid, how can I get it in JSTL? TIA Wolf

  • Slice and dice in webi

    Hi, Can you do slice and dice in webi? If yes, please tell me steps to be required. If no, please tell me for which tool these are possible in BO environment Thanks and Regards, Manjunath