File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calling static methods via object reference

 
Aby Krishna
Greenhorn
Posts: 14
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I want to understand on why is it legal to call static methods via instance (object reference)? Say "myObjRef.myStaticMethod()", is allowed, but how does it work? A static method is at class level and hence the confusion i have.

Any thoughts would be highly appreciated.
 
sanchit latawa
Greenhorn
Posts: 6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well this is merely another syntax "objectinstatnce.mystatic method".You see the compiler know that the method you are calling is static and its equivalent to calling "myclassname.mystaticmethod".So the both can be used in place of one another without the compiler making any noise about it.
 
Rob Spoor
Sheriff
Pie
Posts: 20399
47
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It uses the reference type of the variable. That means that it doesn't use polymorphism. For instance:
 
Christophe Verré
Sheriff
Pie
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code is fun ! Do you expect a NullPointerException ?

 
Jim Hoglund
Ranch Hand
Posts: 525
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code demonstrates what has been described above. Notice
that no object is created. The compiler uses the variable type 'A'. Jim ... ...
 
Rob Spoor
Sheriff
Pie
Posts: 20399
47
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In one previous Java version (was it 1.3?) it was even allowed to use invalid array indexing like this:
Now that will throw an exception as expected, but technically that exception isn't necessary - only the reference type (A) is needed, not the actual reference.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic