I had a question on what "static" does to variables and why "this" can't be applied all the time. And why "static" variables cannot be used in non "static" methods?
Consider the code:
public class Person {
String name;
int age;
public void Person (String name, int age) {
this.name = name;
this.age = age;
}
}
If I add "static" to the constructor then it keeps saying "this" cannot be used in a static contest. What does that mean? Doesn't "static" mean that I don't have to make an instance of the class to use the method? I can just call upon it right?
Also consider this snippet of code:
public class Prog168h {
static String name2;
static int age2;
public void Prog168h (String name, int age) {
name2 = name;
age2 = age;
}
}
In this snippet, there seems to be no error when I make the variables "static" and when the method remains non "static". How come this is allowed but not when just the method is static?
Why does it matter so much that the variables also have to be created "static" because aren't they created in a global scope within the class?
Also why does "this" not work when the method/constructor is "static"?
I would appreciate the help. Thank you very much!
I already looked into what static means but I can't seem to grasp the application here.