Can we override the
static method in Java?
No, you cannot override
static method in Java because method overriding is based upon dynamic
binding at runtime and static methods are bonded using static binding at
compile time. Though you can declare a method with the same name and method
signature in the subclass which does look like you can override static method
in Java in reality that is method hiding. Java won't resolve method call at
runtime and depending upon the type of Object which is used to call
the static method, the corresponding method will be called. It means if
you use Parent class's type to call a static method, original static
will be called from a patent class, on the other hand, if you use Child class's
type to call a static method, a method from child class will be called. In
short, you cannot override static method in Java. If you use
Java IDE like Eclipse or Net beans, they will show a warning
that static method should be called using the class name and not by using
object because of the static method cannot be overridden in Java.
class BaseClass {
|
public static void show() {
|
System.out.printf("Static method from Parent Class");
|
}
|
}
|
class SubClass extends BaseClass
{
|
public static void show() {
|
System.err.println("Overridden Static method in Child Class in
Java");
|
}
|
}
|
public class CanWeOverrideStaticMethod
{
|
public static void main(String args[]) {
|
BaseClass baseClass = new SubClass();
|
baseClass.show();
|
}
|
}
|
OUTPUT: Static
method from Parent Class
Following
are some important points for method overriding and static methods in Java.
1) For class
(or static) methods, the method according to the type of reference is called,
not according to the abject being referred, which means method call is decided at
compile time.
2) For
instance (or non-static) methods, the method is called according to the type of
object being referred, not according to the type of reference, which means
method calls is decided at run time.
3) An instance method cannot override a static method, and a static method cannot
hide an instance method. For example, the following program has two compiler
errors.
4) In a
subclass (or Derived Class), we can overload the methods inherited from the
superclass. Such overloaded methods neither hide nor override the superclass
methods — they are new methods, unique to the subclass.
class Screen {
|
public static void show() {
|
System.out.printf("Static method
from parent class");
|
}
|
}
|
class ColorScreen extends Screen {
|
public static void show() {
|
System.out.println("Overridden
static method in Child Class in Java");
|
}
|
}
|
public class CanWeOverrideStaticMethod
{
|
public static void main(String args[])
{
|
Screen scrn = new ColorScreen();
|
ColorScreen colorScreen =
(ColorScreen) scrn;
|
colorScreen.show();
|
}
|
}
|
No comments:
Post a Comment