Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Method

 
Shrinivas Mujumdar
Ranch Hand
Posts: 328
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Ranchers,
In Java one can invoke static method on instance , but in C# .net it gives error & forces us to invoke it on Classname only.

Why it is so?
Is there any violation of OOPs in either case?
Shrinivas
 
Jerret Halter
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Coming directly from Sierra and Bats SCJP and SCJD book (ISBN 0-07-222684-6).
This is merely a syntax trick to let you use an object reference variable (but not the object it refers to) to get to a static method or variable, but the static member is still unaware of the particular instance used to invoke the static member.


The book is quite good I used it to pass my SCJP book. You can find it here: SCJP

[ March 29, 2006: Message edited by: Jerret Halter ]
[ March 29, 2006: Message edited by: Jerret Halter ]
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm with C#. Nothing to do with violation of OO, in my opinion, but the C# style is more clear.

Static memebers are not a part of an object and it makes sense to prohibit the use of calling them using objects.

Allowing to call the static methods on objects can be misleading. Consider the following piece of code



A programmer, who doesn't have the understading of the effect of trying to override a static method, might write a code like this

There is a possibility that the author of the Client class is thinking that he is calling the method defined in the Child class, but actually, it is the Parent version that will be called (as static methods can be hidden, but can't be overridden)

This can be avoided, by making it mandatory to call static methods only on classes and not on instances.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic