Results 1 to 4 of 4
  1. #1
    Join Date
    Feb 2009
    Posts
    28
    Rep Power
    0

    Default Can we override static method?

    In some books I found we cannot override static methods. But some books are supporting this. The following code is working fine.

    class Compare
    {
    public static void add()
    {
    int a=10,b=15;
    int c = a+b;
    System.out.println("Sum is"+c);
    }
    }
    class Comparesub extends Compare
    {
    public static void add()
    {
    System.out.println("Hello ");
    }
    public static void main(String a[])
    {
    Comparesub.add();

    }
    }

    o/p:Hello

    then why java doesn't support overriding with static methods?

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,783
    Blog Entries
    7
    Rep Power
    21

    Default

    Static methods cannot be overridden, in your example the (static) method add() is hidden by the (static) method in your subclass.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    lovelesh is offline Senior Member
    Join Date
    Nov 2010
    Location
    Delhi
    Posts
    135
    Blog Entries
    1
    Rep Power
    0

    Default

    As JosAH rightly said, compiler would not complain about anything and your program would compile successfully.

    In order to access base class version, you will have to make a call like this: BaseClass.staticMethod
    Without this, your subclass method will get called (because you have hidden base class method).

  4. #4
    Join Date
    Mar 2011
    Posts
    6
    Rep Power
    0

    Default Static Methods can not be Inherited

    Hi friend, you must be clear that the static functions are not bound to any objects of the class rather it's only to the class. And that's the reason why it's called with the class name. So a very clear point that can be stated from the above is that "The Static methods cannot be Inherited". And the overwriting concept comes only when you inherit properties of the superclass. So please don't confuse the inheritance concept and static concept. both are entirely different.

Similar Threads

  1. Replies: 2
    Last Post: 03-26-2010, 06:12 PM
  2. Replies: 3
    Last Post: 02-09-2010, 06:22 AM
  3. Replies: 1
    Last Post: 02-10-2009, 11:03 AM
  4. why we cann't override static methods
    By haoberoi in forum New To Java
    Replies: 2
    Last Post: 11-11-2008, 12:07 PM
  5. Replies: 1
    Last Post: 08-07-2007, 06:05 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •