Do Upcasting effects on Static methods?
Question
Why It calls base class method when we declare method as static in base as well as in derive class and do upcasting.
class Base
{
static void show(){
System.out.println("Base class....");
}
}
class Derive extends Base
{
static void show(){
System.out.println("Drive class....");
}//method hidding.....
public static void main(String[] args)
{
Base b= new Derive();
b.show();
}
}
Solution
You're calling Base.show
, not Derive.show
. Method hiding is not overriding.
§8.4.8.2. of the Java Language Specification gives an example that demonstrates exactly what happens here:
A class (
static
) method that is hidden can be invoked by using a reference whose type is the class that actually contains the declaration of the method. In this respect, hiding ofstatic
methods is different from overriding of instance methods. The example:class Super { static String greeting() { return "Goodnight"; } String name() { return "Richard"; } } class Sub extends Super { static String greeting() { return "Hello"; } String name() { return "Dick"; } } class Test { public static void main(String[] args) { Super s = new Sub(); System.out.println(s.greeting() + ", " + s.name()); } }
produces the output:
Goodnight, Dick
because the invocation of greeting uses the type of
s
, namelySuper
, to figure out, at compile time, which class method to invoke, whereas the invocation ofname
uses the class ofs
, namelySub
, to figure out, at run-time, which instance method to invoke.
OTHER TIPS
There are several issues here to mention:
- static methods are not inherited and not overridden by the sub-classes
- static methods do not need an instance to be called, they need a class
So, basically, calling b.show();
actually means calling Base.show();
Just one more completion to the answers above. It's best to invoke class methods by their class not by an instance variable: Base.show()
not b.show()
to make clear that the method is a static method. This is especially useful in your case when you are hiding a method, not overriding it.