public class A{ static public void method1(){ System.out.println("method a:1"); } public void method2(){ System.out.println("method a:2"); } } public class B extends A{ static public void method1(){ System.out.println("method b:1"); } public void method2(){ System.out.println("method b:2"); } }
public class tmp { public static void main (String[] args){ A a = new B(); a.method1(); a.method2(); } } Output method a:1 method b:2 Could anyone explain how we get the above output? Why don't we get the following output? method b:1 method b:2 Thank you
Anonymous
Ranch Hand
Joined: Nov 22, 2008
Posts: 18944
posted
0
Static methods (functions) are bound to a class, not to individual objects (instantiations) of that class or derivatives thereof. In other words: static methods are not virtual methods (in C++ speak). This enables the compiler to deduce which static method to invoke, i.e. if the compiler sees 'a.method1()' it deduces that a is an object of class A (because you declared it so), so A.method1() should be called. And that's exactly what it does. For non-static methods, the compiler does not deduce anything, it leaves it up to the runtime to figure out what method to invoke. Although a is a variable of class A, it can still hold a reference to object B, because B 'is an' A because B inherits (extends) from class A. Class B overrides method2, so a.method2() causes method2 from class B to be invoked. kind regards
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
With other words: static methods are not polymorphic. You can even invoke a static method on a null reference without getting a NullPointerException.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
0
Originally posted by Ilja Preuss: With other words: static methods are not polymorphic.