• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Statc polymorphism in java?

 
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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()
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic