Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A big confusion

 
Rakesh Jhamb
Ranch Hand
Posts: 154
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Rajah Nagur
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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..
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Java in General (Beginner.)
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic