File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes A big confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A big confusion" Watch "A big confusion" New topic

A big confusion

Rakesh Jhamb
Ranch Hand

Joined: Jun 18, 2003
Posts: 154
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();
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

Rajah Nagur
Ranch Hand

Joined: Nov 06, 2002
Posts: 239
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..

You can't wake a person who is <b><i>pretending</i></b> to be asleep.<br />Like what <b>"it"</b> does not like - <i> Gurdjieff </i>
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Moving to Java in General (Beginner.)

[Jess in Action][AskingGoodQuestions]
Ken Blair
Ranch Hand

Joined: Jul 15, 2003
Posts: 1078
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.
I agree. Here's the link:
subject: A big confusion
It's not a secret anymore!