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

Statc polymorphism in java?

 
Satyajeet Kadam
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
<code>
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();
t.show();
// q =(( t);
//q.show();
}
}
</code>


Problem
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
show()
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Test.show();

instead of

t.show();
[ October 26, 2006: Message edited by: Stan James ]
 
vineela kom
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic