File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Inheritance Problem

 
jake noija
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • 0
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With other words: static methods are not polymorphic. You can even invoke a static method on a null reference without getting a NullPointerException.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
With other words: static methods are not polymorphic.
< tweak >Unless they are overloaded. < /tweak>
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic