BEHOLD CODE
public class Main {
static int bob;
//create a foo
static Foo foo;
//cuz why not have a second foo
static Foo foo2;
public static void main (String args){
foo = new Foo();
foo2 = new Foo();
//creating a local variable with foo2's value +5
bob = foo2.anIntThatWillNeverChageValue+5;
}
}
Foo's class is very simple
public class Foo {
static int anIntThatWillNeverChageValue =5;
public Foo(){
}
}
So you might be thinking "this code compiles fine, whats the problem?". Well java says at the line:
bob = foo2.anIntThatWillNeverChageValue + 5;
in the main class that
The static field Foo.anIntThatWillNeverChageValue should be accessed in a static way
Now I do understand this is generally good practice, and simply accessing Foo's static class by saying
bob = Foo.anIntThatWillNeverChageValue + 5;
would be better practice, more efficient, and simpler. however what about in a polymorphic environment when foo is extended by 3 classes . I wouldn't want to just access the basic Foo's variable, I would want my particular object's variable. Of course the obvious solution to this would be simply making the variable non-static, but in that case you are creating a new variable every time you create a new child of Foo. wouldn't it be more efficient to just access it staticly?
Edit:
quoting from Why should the static field be accessed in a static way?
To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one).
is an answer that is essentially what Im asking. Im trying to use a static method to avoid UNECISARY copies of a non static field. My question is asking why it is against Java conventions to access a static method polymorphically, and also was intended to ask for possible solutions that would be conventionally acceptable and/or more efficient.