aspose file tools*
The moose likes Beginning Java and the fly likes Calling static methods via object reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Calling static methods via object reference" Watch "Calling static methods via object reference" New topic
Author

Calling static methods via object reference

Aby Krishna
Greenhorn

Joined: Jul 10, 2010
Posts: 14
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

Joined: Jul 26, 2010
Posts: 6
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

Joined: Oct 27, 2005
Posts: 19755
    
  20

It uses the reference type of the variable. That means that it doesn't use polymorphism. For instance:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

This code is fun ! Do you expect a NullPointerException ?


[My Blog]
All roads lead to JavaRanch
Jim Hoglund
Ranch Hand

Joined: Jan 09, 2008
Posts: 525
This code demonstrates what has been described above. Notice
that no object is created. The compiler uses the variable type 'A'. Jim ... ...


BEE MBA PMP SCJP-6
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19755
    
  20

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
 
subject: Calling static methods via object reference