• Post Reply Bookmark Topic Watch Topic
  • New Topic

Static methods  RSS feed

 
lahiru nanayakkara
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Above programe prints "myMethod class A" I created object from class B but it execute method in class(template) A.please explain
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please don't use coloured text, which many people find difficult to read. Also use code tags which I shall add to your two posts, and you can see how much better it looks

Start by reading our FAQ which will probably answer your question.
 
Robert D. Smith
Ranch Hand
Posts: 221
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote: [...] Start by reading our FAQ which will probably answer your question.


This is (pretty much) the code from the FAQ. I understand (reasonably well) why it does what it does. But, what caught my attention was the discussion on better coding style (see line 6). I'm not entirely certain on how or why this works. If I understand correctly, as long as I declare an instance of class Foo f = new Foo;, I can make calls directly to Foo without using the declared variable name?
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure I understand the question. If you declare a variable, any static members are bound at compile‑time and calling them is done on the Foo type. If you create it as a Bar, static members are still bound at compile‑time. Instance members are dynamically bound (dynamic ≠ static, which might be why they chose the keyword static) at run‑time, so you get polymorphism. Because of the potential for confusion, you ought always to use the class name: Foo.myStaticMethod(...); and you can do that whether or not there are any variables of type Foo.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!