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.

Similar Messages

  • Overriding static method

    hi all
    can be override static method.if yes then how?plz explain.

    Static methods do hide rather than override - the superclass-and-above methods are, however, visible via explicit referencing. Example:
    public class Foo
         public static final void main(String[] args)
              Foo.foo();
              Poo.foo();
              Foo.bar();
              Poo.bar();
         public static void foo()
              System.out.println("Foo foo");
         public static void bar()
              System.out.println("Foo bar");
         public static class Poo extends Foo
              public static void foo()
                   System.out.println("Poo foo");
              public static void bar()
                   System.out.print("Poo bar, calling foo(): ");
                   foo();
    }Gives
    Foo foo
    Poo foo
    Foo bar
    Poo bar, calling foo(): Poo fooAlways more interesting to try stuff and just see what happens, don't you think? :o)
    Message was edited by:
    itchyscratchy - line wrap pasting error

  • 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.

  • Querry regarding overriding static methods

    Hi ,
    I m overriding a static method defined in superclass ThreadLocal1 as:
    public static void mm()
         System.out.println("bye");
    class Thread1 extends ThreadLocal1{
    tt(){}
    public static void mm()
         System.out.println("hi");
    public static void main(String args[])
         Thread1 t1= new Thread1();
         ThreadLocal1 th1;
         th1=t1;          // t1 is assigned      th1.mm();
         t1.mm();
    }output is : bye
    hi
    I am not getting why ref var th1 is not calling overridden method mm() when th1 is assigned t1 that is subclass instance.
    when i m removing static modifier from mm(0 in superclass then output is : hi hi
    plz clarify why is it so.....
    Edited by: jawatch on Oct 29, 2007 7:01 AM

    jawatch wrote:
    @kajbj :
    but i have overridden static method mm()No, you haven't. You've hidden it. Overriding only applies to non-private, non-final, non-static methods, and they are the only case where you can see the kind of polymorphism you're talking about.

  • About overriding static method inheritance

    I have some class PO2VOPropertyUtilsBean which extends the org.apache.commons.beanutils.PropertyUtilsBean.
    In PropertyUtilsBean,there is a method:
    protected PropertyUtilsBean getInstance() {}I override it in my extend calss PO2VOPropertyUtilsBean:
    protected PO2VOPropertyUtilsBean getInstance() {
          return new PO2VOPropertyUtilsBean();
    }I use Eclipse3.1+Myeclipse4.0,when i choose java5.0 as complier,that all be ok.
    But when i copy the source to my company, my pc uses java1.4 as compiler,it show me errors in the getInstance() method:
    imcompartible return type,it should return PropertyUtilsBean.
    Why?

    Ok, so the getInstance() methods are indeed static.
    As Kaj said, static methods cannot be overridden.
    You would call the method by the classname. For example:
    PropertyUtilsBean bean = PropertyUtilsBean.getInstance();If you write a class PO2VOPropertyUtilsBean with a getInstance() method, the call above will still go to class PropertyUtilsBean, and not to your derived class. After all, how is Java supposed to know that you want to have the method in PO2VOPropertyUtilsBean called? You would need to change the call:
    PropertyUtilsBean bean = PO2VOPropertyUtilsBean.getInstance();

  • How can I override addAll method in LineChart ?

    Hi,
    I need to add some statement when the methods add or addAll are invoked in linechart. How can I do ?
    I thought to do an override of the method, like this
    public boolean addAll(Collection<? extends E> es) {   
            return super.addAll(es);
            <  ..some new statement... >
    but something is wrong.

    'return' returns immediately from your method, so the remaining statements can't be reached. Do
    public boolean addAll(Collection<? extends E> es) {  
            //<  ..some new statement... >
            return super.addAll(es);
    or
    public boolean addAll(Collection<? extends E> es) {  
            boolean result =  super.addAll(es);
            // <  ..some new statement... >
            return result ;

  • 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.

  • 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

  • Redefine static method?

    It seems that I cannot redefine a static method in a subclass in ABAP OO, right?
    Is there a reason for that? Is this like this in other languages as well?

    That's true. You cannot redefine static methods in ABAP OO.
    I can add that a class that defines a public or protected static attribute shares this
    attribute with all its subclasses.
    Overriding static methods is possible for example in Java.
    This simple piece of code illustrates this:
    public class Super {
        public static String getNum(){
            return "I'm super";
         public static void main(String[] args) {
             System.out.println("Super: " + Super.getNum());
             System.out.println("Sub: " + Sub.getNum());
    public class Sub extends Super{
        public static String getNum(){
            return "I'm not";
    The output is:
    Super: I'm super
    Sub: I'm not
    When overriding methods in Java you must remember that an instance method cannot override a static method, and a static method cannot hide an instance method.
    In C# a static member can't be marked as 'override', 'virtual' or 'abstract'. But it it is possible to hide a base class static method in a sub-class by using the keyword 'new':
    public class Super
      public static void myMethod()
    public class Sub: Super
      public new static void myMethod()

  • Static methods in interfaces

    Java cognoscenti,
    Anyone know why I can't declare a method as static in an interface, but I can in an abstract class. Surely, semantically it's the same - defering the implementation of a static method, not an abstract class and an interface. By the way, I'm using JDK 1.2.2 if that makes a difference

    No, it's not the same. You are not "defering the
    implementation of a static method" because static
    methods are never polymorphic.
    Static methods cannot be abstract for this reason, and
    only abstract methods are allowed in interfaces.I didnt't know that. I thought that - because you can override static methods and you can call them onto an actual instance the method binding would be done at run-time, not at compile-time. So I was trying to prove you wrong, but you are correct !
    A short summary of what I've learnt so far:
    - interfaces cannot contain static methods
    - abstract classes cannot contain abstract static methods
    - static methods can be overriden, but they are not polymorphic; this means that the compiler decides which method to call at compile-time.
    /* output
    SuperClass.someMethod()
    SubClass.someMethod()
    SuperClass.someMethod()
    SuperClass.someMethod()
    SubClass.someMethod()
    SubClass.someMethod()
    SuperClass.someMethod()
    public class Test {
      public final static void main(String[] args) {
          // output: SuperClass.someMethod()
          new SuperClass().someMethod();
          // output: SubClass.someMethod()
          new SubClass().someMethod();
          // output: 2x SuperClass.someMethod()
          SuperClass someClass1 = new SubClass();
          someClass1.someMethod();
          showSuper(someClass1);
          // output: 2x SubClass.someMethod()
          SubClass someClass2 = new SubClass();
          someClass2.someMethod();
          showSub(someClass2);
          showSuper(someClass2); // SuperClass.someMethod()
      public final static void showSuper(SuperClass c) {
            c.someMethod();
      public final static void showSub(SubClass c) {
            c.someMethod();
    class SuperClass {
      public static void someMethod() {
        System.out.println("SuperClass.someMethod()");
    class SubClass extends SuperClass {
      public static void someMethod() {
        System.out.println("SubClass.someMethod()");

  • Interfaces and static methods

    Hi All,
    Does anyone know why you can't declare static methods in an interface? Is there a way round this problem?
    Cheers...

    But this won't:public class StijnsClass
      public static void aMethod()
        System.out.println("StijnsClass.aMethod()");
      public static void main(String[] arg)
        StijnsClass stijnsInstance = new StijnsSubClass();
        stijnsInstance.aMethod();
        System.out.println("Nothing else to say, here?");
    class StijnsSubClass extends StijnsClass
      public static void aMethod()
        System.out.println("StijnsSubClass.aMethod()");
        super.aMethod(); // Wrong!!!
    }You will get:
    "StijnsClass.java:21: non-static variable super cannot be referenced from a static context".
    If you remove static from the subclass method definition, you will get:
    "StijnsClass.java:18: aMethod() in StijnsSubClass cannot override aMethod() in StijnsClass; overridden method is static"
    That's the point. You aren't extending the method; you are only hiding it. To make it work, both methods must be instance methods, ergo, static methods cannot be extended.

  • Over riding a static method

    can we override a method marked as static?

    rasundo wrote:
    You're both right, I should have known the difference between '+hiding+' and '+overriding+' ;).
    Now I do (once more again).If you feeling an overriding urge to reply to a forum member's question, first go into hiding and study the JLS.

  • JUNIT : how to call static methods through mock objects.

    Hi,
    I am writing unit test cases for an action class. The method which i want to test calls one static method of a helper class. Though I create mock of that helper class, but I am not able to call the static methods through the mock object as the methods are static. So the control of my test case goes to that static method and again that static method calls two or more different static methods. So by this I am testing the entire flow instead of testing the unit of code of the action class. So it can't be called as unit test ?
    Can any one suggest me that how can I call static methods through mock objects.

    The OP's problem is that the object under test calls a static method of a helper class, for which he wants to provide a mock class
    Hence, he must break the code under test to call the mock class instead of the regular helper class (because static methods are not polymorphic)
    that wouldn't have happened if this helper class had been coded to interfaces rather than static methods
    instead of :
    public class Helper() {
        public static void getSomeHelp();
    public class MockHelper() {
        public static void getSomeHelp();
    }do :
    public class ClassUnderTest {
        private Helper helper;
        public void methodUnderTest() {  // unchanged
            helper.getSomeHelp();
    public interface Helper {
        public void getSomeHelp();
    public class HelperImpl implements Helper {
        public void getSomeHelp() {
            // actual implementation
    public class MockHelper implements Helper {
        public void getSomeHelp() {
            // mock implementation
    }

  • Generics and static methods

    Hi,
    I need a sanity check to make sure I have not missed design pattern.
    I believe that it is not possible to call a static method defined in a generic type.
    For example:
    public class Red extends Color
        public static Color getHue()
    public class Green extends Color
        public static Color getHue()
    public class GenericColorTest<C extends Color>
        public void fooBar()
             Color hue= C.getHue();  // Is this a valid method call ?
    }Since the base class Color can not define static methods, it seems resonable that a generic type can't make the call to get getHue(). Or am I missing something ? Is there a way for the class GenericColorTest's generic type C to call a static method ?
    Thanks
    HB

    I think I can be ever more specific than gafter on this.
    Your call, "C.getHue()", just plain makes no sense. C is "some kind of Color object", and the class "Color" has no function (static or not) called "getHue()". So calling "C.getHue()" is a simple case of you trying to call a function that isn't in the class.
    In fact you can call static functions, but only if they are in the base class require by the generic definition (erm, sorry can't remember the exact term right now). So, for example, if there was a "getHue()" static function in your class "Color", then sure, you can call "C.getHue()" in your code. But since static functions can't be overridden, the "C.getHue()" will do exactly the same thing no matter which actual class C was at the moment, which doesn't seem to be what you want.
    The right thing to do is just make "getHue()" non-static. Then things will work great.

  • Interface with a static method.

    I have tried to define an interface which requires a subclass to implement a static function.
    interface Testable {
    public static TestFrame getTestFrame();
    The idea is the the Testable object must be created with the appropriate constructer arguements, defined by the TestFrame. Thus the TestFrame must be created first.
    When I have tried this, the compiler complains that static is not allowed here.
    Is there a better way to do this?

    When I have tried this, the compiler complains that
    static is not allowed here.You can not have static methods in an interface - it would make no sense since static methods are not polymorphically overridden.
    >
    Is there a better way to do this?Since you need to know the class name in order to instantiate your object anyway, can't you just put the method in the class without it being part of the interface? - If the method is only necessary for object instantiation, then it doesn't sound like it belongs in an interface anyway - clients working with the interface type won't want to use it, so you're just cluttering up the interface.

Maybe you are looking for

  • One or more errors occurred using google drive api

    Hi, I am trying to use the Google Drive API in my C# application with the below code but getting the following error: System.AggregateException was unhandled HResult=-2146233088 Message=One or more errors occurred. Source=mscorlib StackTrace: at Syst

  • Mac Mini good starting choice?

    Hello fellow members, I was thinking of changing from Windows PC to a Mac Mini is the Mac Mini a good Mac to start off with. I have never ever touched a Mac PC and really want one. Am I thinking in the right direction? any advice? Thanks Rich

  • What tags can be used with Notes?

    I have been searching all over to figure out what typs of tags can be used when creating Notes for the iPod. I keep comming back to this document http://developer.apple.com/hardwaredrivers/ipod/iPodNoteReaderGuide.pdf. It is supposed to show availabl

  • Not seeing content in mail folders

    I use default mail with a hotmail account.  I have folders but none of the messages appear when you click on a particular folder.  When I use my PC you can see info in the folders.

  • Beginner's Zenworks - disable status

    here's a very rudimentary question for someone just starting out with Zenworks. What does the "disable" status do for policy parameters? I understand the concept of "ignore." I am not sure how "disable" differs from "ignore." thanks in advance