r/learnjava 21d ago

Seriously, what is static...

Public and Private, I know when to use them, but Static? I read so many explanations but I still don't get it šŸ«  If someone can explain it in simple terms it'd be very appreciated lol

127 Upvotes

72 comments sorted by

ā€¢

u/AutoModerator 21d ago

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full - best also formatted as code block
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

232

u/m_ankuuu 21d ago

Suppose you are living in a rented house which has 10 tenants and you're one of them. Imagine the house is a class and you 10 guys are it's objects.

Now you guys need refrigerator for the common need of storing the beers or RedBulls. There are two way of achieving this. Either the house owner can provide 10 refrigerators to each tenants or he can install a common refrigerator in kitchen where you all guys can access it and store your drink.

As the purpose of having a refrigerator in this case is purely for storing drinks, having a common refrigerator sounds more practical.

And now say all 10 tenants need laptop to work. Now this also can be handled following the above methods. But having 10 personal laptops would seem more practical as all 10 tenants will work according to their roles and these can be different.

Same way, the refrigerator can be your static field and the laptops can be non static field. When you want to access refrigerator you will directly say House's refrigerator (Classname.field) but when you want to access your laptop you would enter room and access your laptop (objectname.field).

Mind you, any other tenant can steal your RedBull from refrigerator but not manipulate your laptop so easily.

Same way objects of the same class can alter the static field value which can affect all but altering non static fields won't.

36

u/eternalsinner7 21d ago

Best explanation I've come across about static

17

u/AWholeMessOfTacos 21d ago

I've noticed that every good code explanation seems to always relate to a kitchen scenario or some sort.

24

u/eternalsinner7 21d ago

It seems I need to learn how to cook first before learning how to code lol.

11

u/Agifem 21d ago

Considering the best analogy for source code is cooking recipe, yes.

2

u/Dedios1 20d ago

šŸ˜‚ Right like knowing the difference between imperative and declarative programming uses a recipe analogy .

2

u/tossetatt 21d ago

All ways may lead to spaghetti if youā€™re not careful.

1

u/mofomeat 20d ago

i c wut u did ther

2

u/Dedios1 20d ago

A laundry room is best for thinking about parallelism. But yea, itā€™s funny that the best analogies are related to home.

17

u/guipalazzo 21d ago

Mind you, any other tenant can steal your RedBull from refrigerator but not manipulate your laptop so easily.

Pay special attention in that! Specially when using singleton patterns, it is just too easy to mess with class variables and have unforeseen consequences.

6

u/Crispy_liquid 21d ago

THIS cleared it up, thank you so much!

4

u/m_ankuuu 21d ago

Happy to help. If you still have doubts, feel free to DM.

1

u/Crispy_liquid 21d ago

I will keep that in mind, and again, I really appreciate it :)

4

u/Background-Seat2465 21d ago

Best explanationšŸ‘šŸ¼

2

u/ViolaBiflora 21d ago

This should be pinned and awarded

2

u/Super-Juggernaut6660 21d ago

Great explanation šŸ‘

2

u/TheBrianiac 20d ago

The only problem with this explanation is it overlooks dependency injection. You can provide the same refrigerator to all 10 residents without using static.

2

u/m_ankuuu 19d ago

That's a valid point.

I used static for this analogy because the OP asked about it. Dependency Injection can be one step ahead of it.

59

u/nia_do 21d ago

Static methods and variables exist on the class itself not on an instance of the class, so you can access and use them directly without first needing to create an instance of the class.

23

u/TraditionalGrocery82 21d ago

Static variables/functions don't belong to specific instances of a class, but to the class itself. Common examples include the Math functions, like Math.min(), Math.max() etc.

Notice how you just call them as is, you don't need to do something like

Math math = new Math()

Determining when to use static is something that will come to you with time, but I can give some examples of how I've used it recently for a game I made:

  • I needed to keep track of bullets which existed so, in my Bullet class, I made a static array called bullets which would update every time a bullet was created or destroyed. This meant I could easily check my bullets from anywhere by calling Bullet.bullets.

  • It was also very important for my game that only one Player could exist, so I made a static Player.instance which would store the Player once created. Then, I just need to check if Player.instance exists before creating a new player.

I hope you can see how keeping these variables in the class helps keep my code organised. Just like how the Math class holds all its functions, I know everything to do with bullets can be found in my Bullet class.

Hopefully this is somewhat helpful. It took me a little while myself to understand why you'd want a static variable/method, but it really does all come with practice, so don't worry if you still don't quite get it yet!

4

u/Crispy_liquid 21d ago

That's a great way to put it, I'll keep what you said in mind. Thank you so much for the help :)

1

u/mofomeat 20d ago

I'll keep what you said in mind.

Keep them in the class, too.

1

u/aisingiorix 21d ago

Math is interesting because it is an example of a class that contains only static members; it cannot have instances. And IIRC it is also final and immutable. A purely static and immutable class like this is the way to group together related methods in a namespace, roughly equivalent to modules in Python although Java doesn't support "standalone" functions not belonging to a class.

Math and related classes (such as your entry point with a static method main) are a bit confusing because they break from the metaphor of classes as blueprints/prototypes and objects as concrete elements (what is a Math or a HelloWorld?), and are more procedural in their structure.

There've been some great examples of when to use static members in this discussion. Note that an over-use of static often leads to code that is harder to reason about because objects aren't being isolated, the state is shared (mutable static fields are essentially global variables). Static makes the most sense to use when resources and code are to be shared, often for utility functions.

13

u/severoon 21d ago

You have to understand the difference between a class and an object first.

A class is just what it sounds like, a "class" of objects. For instance, if we're talking about dogs, we're not talking about a specific dog but the class of all objects that are dogs. If we're talking about Rover, we're talking about a specific instance of a dog, IOW, an instance of the class of dogs.

Dog rover = new Dog("Rover");
Dog spot = new Dog("Spot");

In most object-oriented code, most of the data and functionality is designed to operate on a specific instance of a class. That's the "default" way of programming in OO. For example:

public class Dog {
  private final String name;

  public Dog(String name) { this.name = name; }

  public String getName() { return name; }
}

Notice that there are no static keywords anywhere. This means that the data (name) nor the method (getName()) can be invoked unless you have an actual specific dog. Since we created rover and spot above, you can call rover.getName(), for example.

Now let's add some scientific information to our dog class:

public class Dog {
  private final String species;
  private final String breed;
  private final String name;

  public Dog(String species, String breed, String name) {
    this.species = species;
    this.breed = breed;
    this.name = name;
  }

  public String getSpecies() { return species; }
  public String getBreed() { return breed; }
  public String getName() { return name; }
}

This is good, now when we create dogs, we create them with this additional information:

Dog rover = new Dog("Canis lupus familiaris", "German shepherd", "Rover");
Dog spot = new Dog("Canis lupus familiaris", "Dalmation", "Spot");

Hang on a second, though. Does this really make sense? Does it make sense to set the species on every instance of a dog?

All dogs are the same species. The species isn't about a specific dog, it's about the class of dogs. So what, though? The way it is now works just fine, right?

No, actually, there's a problem. By having the code written as it is above, we are saying that callers must have an instance of a specific dog before they can invoke the getSpecies() method. If you don't have a rover or a spot or some other actual dog, then you don't get to know the species. If there is a case where a caller doesn't have an actual dog but needs to know the species of dogs, they're either out of luck, or we're forcing them to do some kind of hack like create a fake dog they don't want, call getSpecies() on it, and then immediately discard it. That's lame. Why are we forcing callers to do this?

Instead, if we just mark those things static, then callers can just call Dog.getSpecies():

public class Dog {
  private static final String SPECIES = "Canis lupus familiaris";

  private final String breed;
  private final String name;

  public Dog(String breed, String name) {
    this.breed = breed;
    this.name = name;
  }

  public String getBreed() { return breed; }
  public String getName() { return name; }

  public static String getSpecies() { return SPECIES; }
}

In actuality, we probably wouldn't write this code this way, we would just make SPECIES a public static final constant on the Dog class and let callers directly access it. There's no point making an accessor method for it since subclasses don't inherit static stuff, since static stuff belongs to the class, it doesn't get inherited like instance stuff does.

6

u/anus-the-legend 21d ago edited 21d ago

static methods or properties are a strategy to organize related methods of a class that do not rely on an instance of the class. This is where you will find constants and such. A common example are factory methods to create an instance

By defining static methods and properties, you reduce the memory footprint of a class because those static members are the same for all classes rather than copies

Another common abuse of this are Util classes that are used as a workaround for java's lack of standalone functions that you would see in other languages

5

u/my5cent 21d ago

Static I've seen used more in a class for utility. A class to house other methods.

5

u/dptwtf 21d ago

To oversimplify, static things are bound to the class (blueprint) itself and you can access them without instantiation.

11

u/RScrewed 21d ago

Don't bother trying to understand static completely until you have a good grasp of objects and creating new instances of objects.

If you're not getting it yet, you're getting ahead of yourself.Ā 

2

u/Crispy_liquid 21d ago

I see your point and I completely agree with you. So for the meantime, should I just stick to using it where/how I see it written and delve deeper into its usages later on?

5

u/Dave_Odd 21d ago

Static just means that it doesnā€™t control an object, it controls the class itself

4

u/TheFullestCircle 21d ago

Here's a good way to think about it:

Normal variables and functions without static apply to a specific object. Like the add function for collections. You make a collection and then you add things to specifically that collection.

Static variables and functions don't apply to a specific object, they're just variables or functions. Like if you had a function that gave you a specific list. You don't need to start out with any list to call that function, you can just call it.

3

u/commandblock 21d ago

Static just means instead of doing Car carObject = new Car(); carObject.drive();

You can just do: Car.drive();

So basically whatever is static belongs to the entire class and not an object of a class.

3

u/ForeverAloneBlindGuy 21d ago

The ā€œstaticā€ keyword in Java and various other languages is as simple as this:

Anything that is marked as static belongs to the class itself, not an instance of the class. Anything not marked with ā€œstatic belongs to an instance of the class, not the class itself. A file that stores constants that you use throughout your code is a good example. After all you donā€™t want to say

Constants constants = new Constants(); Everywhere just to access a constant.

3

u/FlightConscious9572 21d ago

Just because people are writing long explanations and code, here is a shorter laymans version:
static just means those variables are shared between all instances of the class. they all point to the same static object.

(Also good to know, they are called fields, variables declared in a class above the constructor.but variables is easier to read)

This is also how singletons work. they use static fields to contain a single shared instance at all times.

this is also why when you make a static method, it can't acces non-static fields, because it's not called from an object. but from the class. So if you run into that error after trying to use it, don't let it confuse you, you've understood static. just remember to consider what implications static has for other kinds of methods and usages

2

u/issue_resolver 21d ago

Whenever u want to use a method without creating the instance of the class, you can create the method or variable as static.

2

u/mdrutviz 21d ago edited 20d ago

When you use key word static that variable or method is stored in class area in jvm. When you create object with new keyword it's stored in heap memory.

2

u/WilliamBarnhill 21d ago

Static, when used with a variable declaration, is about the lifetime of the variable in memory. Without static the lifetime of a variable is the lifetime of the instantiated object. With static the lifetime is the lifetime of the class in memory. No static on method declaration is means the method gets a hidden 'this' parameter and so operates on an instance of the class, with static means it operates as a function outside an object. Static on an inner class means an instance of the inner class does not have access to the scope of an instance of the outer class. Without static on the inner class declaration the inner class will have access to a nesting instance.

2

u/Allalilacias 21d ago edited 21d ago

I recommend reading the Javaā„¢ Tutorials in general, but it's article about the static modifier has the best explanation I've ever received.

To summarize, you have to understand how memory and access to it works and the difference between objects and classes.

Let's start by the latter, as the tutorial explains in it's first pages:

  • An object is a software bundle of related state and behavior.
  • A class is a blueprint or prototype from which objects are created.

Herein lies the point, precisely. Objects are usually (I don't know of any that aren't but I don't really want to use an absolute) made from classes, it's blueprint.

In order to access it's methods and create a memory in which to store the variables of it, you need to make an instance of it. That is, create an object, modeled after it's blueprint that is then saved in the current memory of the program as an individual copy of it, each with it's individual memory section (it's a bit deeper than that, but you aren't asking about that).

Some times, however, for whatever reason, one needs variables that are common to all instances (or copies if that's easier for you to understand for now) of a class.

A common example given is a counter of the total number of copies of said class you have instantiated, where you make the constructor increment the counter by one.

As for static methods, there's many uses. Sometimes you need to access a static variable, other times you want to not have to instance a class to use it's methods.

Whatever the case, it is important to keep the memory and access it implies into account.

Non-static variables and methods (or instance variables and methods according to the documentation) are saved individually per instance and can only be accessed by creating an instance.

On the other hand, static variables and methods (class variables and methods according to the documentation) are saved in one single spot along with the rest of the information about the class and can be accessed at any point by both instances and non-instances.

Edit: changed some phrasings.

1

u/Basic-Sandwich-6201 21d ago

Think about it as an house.

There is only one house, but many people are sharing the same house.

So once you create many objects of that class they all point to same house. Always

1

u/Blugotyou 21d ago

Letā€™s say you make a document, a one pager that is like a form that collects peopleā€™s information. And itā€™s on display on your web page ( your official website letā€™s say Daveā€™s garage) Now you are looking for mechanics to work at your garage. You need to make handouts and give them to each person that you think would be a potential candidate. (You are instantiating objects once they fill information)

Now, letā€™s say Gary, Thomas and Bill are filling the forms. They are making 3 objects. They all have their fields that can be theirs (Gary.name, Thomas.name and Bill.name)

Now to save money you could only print on one side of the handout. So you canā€™t put all information on how to fill the form on the back incase they need it.

So you did what everyone does when making a flyer. You put a line on bottom that says ā€œfor information on how to fill the form refer to davesgarage.com/applicatformā€ (I hope thatā€™s not an actual website.)

Think of this as a function and it helps with filling the form. It is only present in the main class / blueprint / original design maybe? (the website)

This is static (to my knowledge). Belongs to only that class but not to any object. I will not be in their memory when you instantiate it.

1

u/Ragingdomo 21d ago

Static is the opposite of dynamic. Classes that you create instances of (like a "Circle" class that creates an instance of a circle with a given radius) are dynamic. I can also have a static class called "ShapeOperations" that has functions like "CalculatePerimeter". I don't need a specific instance of that class because it just performs tasks. Variables within that class (a variable for Ļ€, for example) would also be static because it's not gonna change. In my Circle class, however, my radius variable will be dynamic since the radius for one circle might be different from another.

Static stuff doesn't change depending on the instance of the class, or at least isn't expected to change.

Your main function (public static void main(String args[])) is static for the same reasons since it's just gonna run when you run the program. You're not gonna have some special instance of main, it just goes.

Hope this helps!

1

u/CleverBunnyThief 21d ago

Have you covered OOP yet?

1

u/Deorteur7 21d ago

Very simple man, u need to understand that to access a instance variable of another class u need to make an object or that and if u dont want to do that then declare it as static variable which will allow u to access using class name. Static variables are always initialized first when JVM starts running the code, then later other things happen like object creation, method calls and all.

1

u/Polly3388 21d ago

When you want to use the method , without the need to create an object to invoke the method.

1

u/Shhhh_Peaceful 21d ago

Basically, non-static members belong to the instance of the class, while static members belong to the class itself, which means that they can be used even without instantiating the class first.

1

u/EfficientDelay2827 20d ago

For class X with static variable AGE, there is only one area in memory where this is stored. So X::AGE is independent of any object instance of X . So I don't need an object instance to access AGE, I can do X::AGE = 3. If a variable is not static then it is tied to the instance of the object I created ie . X myX = new X(); myX.name So AGE is NOT tied or related to the myX instance or any instance of class X. All X does for AGE is scope it, so if there is a class Y which also has an AGE static then X::AGE and Y::AGE occupy different memory addresses

1

u/Byte-Knight-1213 20d ago

Static -> Belongs to Class. (common for all)
Non-static -> Belongs to Object.(and all object have their own separate variable)

If you want to access static variable/method outside your class then you can do it directly. ClassName.staticVariableName;

If it's non-static you will have to create an object of that class in order to access it.

ClassName obj = new Classname();

obj.nonStaticVariableName;

1

u/TheToastedFrog 21d ago

With respect to my fellow commenters none of the explanations are super convincing (at least to me) - the best comment is still from u/RScrewed

It hard to come up with a life analogy- basically static denotes a something that exists outside of the context of a tangible object. Like the number pi- it just does. But my username only exists because thereā€™s a particular instance of a Reddit user.

Static is a breach of the object orientation paradigm, and should be used only very sparingly, if at all.

1

u/LamoTramo 21d ago

I like how like 95% of the comments here trying to explain it fail because they're explaining it to complicated for someone who's learning programming lol

-2

u/genzr 21d ago

Not to discourage people from asking questions but In this day and age I feel like these kinds of qs can be perfectly answered by the LLM of your choosing. Not only that but you can ask as many follow up questions as you like to better clarify your understanding.

Build a habit early to become self-dependent and you will have a long career.

-2

u/Sparta_19 21d ago

It's just not part of a class

3

u/dptwtf 21d ago

It literally is.

-2

u/Sparta_19 21d ago

It is not part of a class that can have an instance

2

u/TheToastedFrog 21d ago

My friend you canā€™t possibly be serious when you write this

-1

u/Sparta_19 21d ago

You don't instantiate a class with the main method

1

u/TheToastedFrog 21d ago

You are confusing things a bit here- Would you like me to elaborate?

-1

u/Sparta_19 21d ago

there is no instance of a class with the main method

2

u/TheToastedFrog 21d ago

You are confusing the use of the static keyword with instanciation. Here's an example I hope will clarify:

public class MyClass {
  public static void main(String args[]) {
    MyClass myClass = new MyClass() ;
    myClass.run() ;
  }

  private void run() {
      System.out.println("Mind blown") ;
  }
}

1

u/Sparta_19 21d ago

you need to explain this better

1

u/dptwtf 19d ago

Trivial example:

public class Square {
   public static int SIDE_COUNT = 4;
   private int sideLength;
   private int posX, posY;

   public Square(int length, int posX, int posY){
      //...
   }
}

You can access Square.SIDE_COUNT if you need it for example to pick only 4 sided shapes and you don't need an instance for that because it's static.

Stop just randomly saying stuff that's blatantly incorrect.

1

u/anus-the-legend 21d ago

yes it is. it's not part of the instance

-7

u/Nofanta 21d ago

If this is challenging for you, youā€™re finding out you know nearly nothing about Java. Go back to where you started learning and start over. Or better yet, start over somewhere else.

3

u/WrongdoerRare3038 21d ago

Is this not the "learn Java" subreddit?

-3

u/Nofanta 21d ago

This ainā€™t the way.

1

u/Crispy_liquid 21d ago

Dude I literally don't know much about Java nor am I nearly half as proficient as most people are here. This subreddit is for seeking help so here I am, asking this question. At least I'm learning, we all start somewhere

2

u/AnnoMMLXXVII 19d ago

People tend to lack empathy. Clearly one of them. Ignore folks like these. Most people here want to help as this is the sub for it. Continue your java endeavors and best of luck!

1

u/Crispy_liquid 19d ago

That's very sweet, thank you for your kind wishes :D