Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static method

 
Arun Maalik
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • 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
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • 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.
 
vignesh hariharan
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • 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...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic