r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

13

u/Silent__Note Apr 05 '22

Static (I'm beginner in Java)

6

u/EdenStrife Apr 05 '22

Static means you can access a function on a class without creating an instance of the class.

So for example the Math class. You want to be able to do arithmetic without creating a Math object in memory to do it for you.

11

u/ThatWolfie Apr 05 '22

https://www.reddit.com/r/learnprogramming/comments/twuf18/-/i3hzf6v this dude explains it well.

static functions are functions that do not need the state of the object. so if your method doesn't use this at all, it can be and should be (in most cases) static.

static methods don't require you creating an instance of an object either.

3

u/Emerald-Hedgehog Apr 05 '22 edited Apr 06 '22

In very short with a class as example:

As soon as the program starts, a Class with the static prefix is instantiated. If you want to use a static Class it doesn't need to be instantiated (no new Class() needed, you can just use that class because it's already there from the beginning).

Just try it and experiment with it, that makes it much easier to understand. Here's what you can try for example:

There's more to it than static classes, you can also just have static variables for example. A normal class can have static variables.

Image you have a Class 'Person' with the static int 'personsBornCounter'. Now imagine in the constructor of the Person Class, you increase this variable by one. You can call this variable on any person and all will return the same number.

Pseudo code:

Class Person {  
  Static Int personsBornCounter = 0  
  Constructor() {  
    personsBornCounter += 1  
  }  
}

Now create person a b and c and call the personsBornCounter on all of them - it should be 3 on all of them!

Also sorry for the lack of formatting, I'm on my phone.

Edit: Formatting

→ More replies (1)