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 Inheritance Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Inheritance Problem" Watch "Inheritance Problem" New topic

Inheritance Problem

jake noija

Joined: Jan 24, 2003
Posts: 1
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();
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
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Jul 11, 2001
Posts: 14112
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
Originally posted by Ilja Preuss:
With other words: static methods are not polymorphic.
< tweak >Unless they are overloaded. < /tweak>

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
I agree. Here's the link:
subject: Inheritance Problem
It's not a secret anymore!