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)

1

u/AlSweigart Author: ATBS Apr 05 '22

It's confusing because, in a way, static methods are pointless.

Methods are functions that belong to the objects of a particular class. You call an object's method and it could do stuff based on the data in that object (i.e. the state of the object).

But static methods aren't connected to a particular object. Really, a "static method" is basically just a function in other programming languages. But in Java, everything exists in classes so you don't have standalone functions. I have strong disagreement that this is a good way to design a language, because you end up having to have weird things like static methods.

For example, take an "absolute value" function: it takes an integer or a float or whatever and returns the absolute value of it. There's no need for this to be a method of an object; it could be a function that just takes an argument and returns a value. It doesn't need or rely on the state of any particular object.

But in Java "everything is a class" and there are no functions, so instead it has to become the static abs() method in the Math class. In fact, everything in the Math class is static. So the Math class isn't a class in the sense of "a blueprint for instantiating objects" because you never instantiate Math objects. You never run Math foo = new Math();. Instead, Math acts as a way to group a bunch of static methods (which should be functions) together. This class is doing what modules/packages in other languages do, rather than acting as a class you make objects from.

Opinions can differ, but I really think having classes for two different purposes is confusing. Especially when you have classes that have both static and non-static methods. A lot of Java's "design patterns" are really just workarounds for the language's strict adherence to the object-oriented paradigm where "everything is a class". (And that's not even true, which is why we have int primitive data types and Integer classes. Ooof, what a mess.)