• 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
  • Ron McLeod
  • Liutauras Vilda
  • Paul Clapham
  • paul wheaton
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Rob Spoor
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:

Static methods

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Marshal
Posts: 78651
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 235
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 78651
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Let me tell you a story about a man named Jed. He made this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic