0

I've learned that I should use Object(instance) for using instance field in static method.

For example:

INSTANCE FIELD(==speed)

that is declared in public class Car, should be used through Object in static method (ex. 'public static void main(String[] args) )

like this.

Car myCar = new Car();

myCar.speed = 60; 

So, the reason I should use object is because static method is located in CLASS and for being shared to objects, but on the other hand, instance field is just Frame that is not substance?

For using this instance field in static method, do I have to make the instance that is called 'object'?

In other words, is this process right?:

instance field -> OBJECT( substantialization)  -> static method. 

I'm wondering what I understood

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jinwon Kim
  • 23
  • 4
  • 2
    A static field only exists once per class. So in case of your car speed you should ask yourself: Do all cars in the world have the exact same speed all the time, or does every car have its own speed? If the first is the case you can use a static field, if the second is the case then you cannot use a static field and need to use a instance field. (And yes the answer is obviously that speed cannot be static because it is perfectly possible for one car to have a speed of 0, also called parking, while another one drives by with 30kmh - So every car instance needs is own value for speed) – OH GOD SPIDERS Jun 12 '20 at 14:25
  • What does 'use `Object(instance)` for using instance field in static method' mean? – user207421 Jun 13 '20 at 10:05

1 Answers1

0

static methods are used for 3 reasons:

  1. "stateless" methods. A good example of this would be Math.sin
  2. Global "singletons": singleton is in quotes because the singleton pattern is not used everywhere in java. An example of where it is could be Runtime.getRuntime() an example of where it isn't might be Thread.getUncaughtExceptionHandler (implicit singleton)
  3. Program entry point (public static void main) : It makes sense for a program to start outside of an object context (rather than innside)
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80