jQuery in Action, 3rd edition
The moose likes Java in General and the fly likes Statc polymorphism in java? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Statc polymorphism in java?" Watch "Statc polymorphism in java?" New topic

Statc polymorphism in java?

Satyajeet Kadam
Ranch Hand

Joined: Oct 19, 2006
Posts: 224
class Test
static void show()
System.out.println("Show method in Test class");

public class Abs extends Test
static void show()
System.out.println("Show method in Abs class");
public static void main(String[] args)
Test t= new Abs();
// q =(( t);

Q1) If we remove keyword static from base and child class outut is
"Show method in Abs class".

Q2) If we add keyword static it invokes Show method in Test class

Both methods have same signature. So it it should invoke child class
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
This line

Test t= new Abs();

tells the compiler that static operations are done on class Test. Period. It wires static methods and variables up to class Test at compile time. Try the static t.show() with "Test t = null;". The call is wired to Test, not the instance.

Non-static operations are done on the actual class of the instance. The compiler doesn't wire method calls up to actual method code at compile time, but wires up to the class dynamically at run time.

Why? I'm not sure, but it was the language designer's choice to make. But because this can be confusing, the preferred and more semantically correct way to reference static methods and variables is by the class, not a variable.


instead of

[ October 26, 2006: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
vineela kom

Joined: Aug 04, 2006
Posts: 7
In the above code Test t = new Abs()

When the methods are defined as static,
Since "t" is defined as type Test,it doesnt matter for the compiler even the instance referred by t is actually Abs.The compiler only uses the declared type and t.show() ,t is of type Test so show method of Test is called.
I agree. Here's the link: http://aspose.com/file-tools
subject: Statc polymorphism in java?
It's not a secret anymore!