Results 1 to 4 of 4
Thread: Can we override static method?
- 06-17-2011, 08:46 AM #1
Member
- Join Date
- Feb 2009
- Posts
- 25
- Rep Power
- 0
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?
- 06-17-2011, 09:12 AM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,414
- Blog Entries
- 7
- Rep Power
- 17
Static methods cannot be overridden, in your example the (static) method add() is hidden by the (static) method in your subclass.
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 06-22-2011, 07:42 AM #3
Senior Member
- Join Date
- Nov 2010
- Location
- Delhi
- Posts
- 135
- Blog Entries
- 1
- Rep Power
- 0
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).
- 06-24-2011, 02:29 PM #4
Member
- Join Date
- Mar 2011
- Posts
- 6
- Rep Power
- 0
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
-
method not abstract, does not override actionperformed method.
By Theman in forum New To JavaReplies: 2Last Post: 03-26-2010, 05:12 PM -
Java class HashIt with a static recursive method and a static iterative method
By kezkez in forum New To JavaReplies: 3Last Post: 02-09-2010, 05:22 AM -
static method sparks error on overriding non-static method
By MuslimCoder in forum New To JavaReplies: 1Last Post: 02-10-2009, 10:03 AM -
why we cann't override static methods
By haoberoi in forum New To JavaReplies: 2Last Post: 11-11-2008, 11:07 AM -
Error: Non-static method append(char) cannot be referenced from a static context
By paul in forum Advanced JavaReplies: 1Last Post: 08-07-2007, 05:05 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks