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

static method

 
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey Sir
As we know that static function in a class is concerned with class not with object then if we declear a function in a class as static then in main it should call only with class name or free not with object but it is calling with object also why?
like
public class first
{
static int abc=90;
public static show()
{
System.out.println(abc);
}
public static void main(String[] args)
{
first p=new first();
first.show();//ok
p.show();//working but why?
}
}//first
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Welcome to JavaRanch!

The answer is just "because that's how it works." You can call a static method of a class by providing a variable of that class's type. The object is actually not necessary -- the variable can be null and this will still work.

Many Java developer's environments (Eclipse, IDEA, etc) will issue a warning when you do this. There's nothing wrong with it; it's just bad style.
 
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hey mallik..

a static member can be accessed either by

*) obj.staticmethodname();
*) classname.staticmethodname();

this is because there is no use of creating an object to that class in order to call the static method. if u create 100 objects of that class and make changes to the static method by one among the 100 objects, then all the rest of the 99 objects will also get changed automatically. the word static holds the meaning of being same through out the class, irrespective of how many objects modify it. so ultimately there is no use of creating an object and accessing a static method. that is the reason why ppl say that static member belong to the class and not objects.

and eg:


i hope u got it cleared...
 
reply
    Bookmark Topic Watch Topic
  • New Topic