Forums Register Login

A big confusion

+Pie Number of slices to send: Send
Hi All,
Please have a look at the following code :
public class SuperClass {
public static void method() {
System.out.println("SuperClass method");
}
}
class SubClass extends SuperClass {
public static void main(String args[]) {
SubClass subClass = new SubClass();
subClass.method();
}
}
The above code prints SuperClass method.

How it is working. As most of the books say, that inheritance and overriding does not apply to static methods. So the method was not inherited in SubClass, so how this code is working.

Waiting for a detailed reply.
Thanks and Regards
+Pie Number of slices to send: Send
Definitely - Inheritance & Overiding does not make sense to static methods or static variables.
The only way (ignoring reflection api) to call a static method is only if you know the class name at compile time. So if you know the class name at compile time, it makes no sense to inherit static method.
Although you can call static method on an instance variable, it is considered as an bad practice. It is also not practical to inherit and overide because there is no way to call static method polymorphically anyway.

That was theory, now comming to your question:
All static method calls are determined at compile time.
In your example case compiler is smart enough to find out that SubClass is also of type SuperClass and since there is no method by name method() in SubClass, it checks it in SuperClass.After it finds that it is a static method, it replaces the subclas reference to SuperClass in the generated bytecode.

Hope this helps..
+Pie Number of slices to send: Send
Moving to Java in General (Beginner.)
+Pie Number of slices to send: Send
Static members belong to the class not an instance of the class. Despite what you may have read static methods are inherited but they cannot be overridden. If you were to declare a method with the same name and signature in SubClass it would hide the method in SuperClass because the two methods belong to two different classes.
Get out of my mind! Look! A tiny ad!
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 647 times.
Similar Threads
question from Dan's exam - ClassCastException
Why we got warning when calling a static method through an instance?
jtips 1, q26
this and super
Constructor
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 08:13:15.