0

Say I have two classes, First and Second. In Second I've written a method as follows:

public static void hWorld(){
  System.out.println("Hello World!");
}

Then from the main method in the First class I instantiate the Second class and call the hWorld method with:

Second get = new Second();
get.hWorld();

Why couldn't I simplify this by making the hWorld method non-static as follows:

public void hWorld(){
  System.out.println("Hello World!")
}

Then from the main method in the First class I call hWorld with:

Second.hWorld();

I guess I don't completely understand what static is used for and when it's better to use. I know by definition that making a field static, it can be called throughout the class as opposed to just an instance of the field. But in practical terms I'm not seeing or understanding that. Can someone please break it down? Thanks.

user229044
  • 232,980
  • 40
  • 330
  • 338
dbconfession
  • 1,147
  • 2
  • 23
  • 36
  • You're right -- you don't understand what static means. A regular instance method must be invoked using an instance, not the class name. Eg, you cannot invoke an instance method as `Second.hWorld();` since `Second` is a class name, not the name of an instance variable. (You appear to have things exactly backwards, in fact.) – Hot Licks Jul 02 '14 at 02:27
  • (This is confused slightly because the `javac` compiler will, as a "convenience", interpret `Second get = new Second(); get.hWorld();` as if it were `Second.hWorld();` if `hWorld` is a static method.) – Hot Licks Jul 02 '14 at 02:29
  • @HotLicks but both work. I tested them before posting this. I'm asking why. And in what instances each should be invoked. Your response doesn't even address my question "what does static mean in practical terms." Please be productive or do not respond. – dbconfession Jul 03 '14 at 04:50
  • I was "productive". The first form is compiler trickery. Internally the call is converted to Second.hWorld(). I kinda wish the compiler didn't do this, as it causes a lot of confusion. (And you CANNOT invoke a non-static method using `ClassName.methodName();` -- that will not work under any circumstances.) – Hot Licks Jul 03 '14 at 11:27
  • @HotLicks thank you. I didn't realize the second response was also you. – dbconfession Jul 03 '14 at 18:58

0 Answers0