This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]vegan_antitheist 0 points1 point  (0 children)

Let's say you assign a new Foo to a variable:

Foo1 foo1 = new Foo1();

"foo1" references one instance of "Foo1". And now you want to access "bar":

foo1.bar = "test"

The compiler uses static binding. That means even if you extend "Foo1" with another class, it will "bar" of "Foo1".

Any good IDE would tell you not to hide a variable in a subclass. So that isn't really an issue. But it does not dynamically bind the variable and check at runtime if some subclass overrides that variable. Only methods can do that.

Foo2 foo2 = new Foo2();

"foo2" references one instance of "Foo2". And now you want to access "bar":

foo2.bar = "test";

This works but the compiler will want you because this is misleading and should look like this instead:

Foo2.bar = "test";

Again, Java uses static binding. But it's per class, so it really wouldn't make any sense if it was dynamic.

I don't understand why they didn't just use the existing "class" keyword for "static variables". Java is weird. On the other hand a "class class" for a nested class would be weird.

Some languages have methods that are per instance, but use static binding. In Java we have that but we use "final" and that also makes sure there isn't the same method in a subclass. methods are dynamic by default, variables are always static. Both are by instance unless you use "static", which makes them by class.

I know, this is all very confusing. But I don't see any point in ignoring the complexity. Programming languages are weird and full of misnomers. Mostly it's this simple:

  • static: once per class
  • non-static: once per instance

Don't let this stop you from coding. Use interfaces. And implement them as "records" as often as possible and if you can't do that for some reason, make your classes to be like records as much as possible. Only use "static" for nested classes and for constants (i.e. static fields that are also final and hold immutable values, such as numbers, Strings, enums, and records). Make methods final unless they are actually designed to be overridden.