0

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.

Iofacture
  • 655
  • 3
  • 13
  • 39
Asker123
  • 350
  • 1
  • 3
  • 15
  • This question will be probably downvoted too many times or closed for duplicate. Anyway, `static` is a modifier for class level while non static is for instance level – Federico Piazza Oct 25 '16 at 19:53
  • a static var exists in ALL instances/copies of that class, instantiated or not. therefore `this` is redundant, since `this` points to a SPECIFIC instance of the object. – Marc B Oct 25 '16 at 19:53
  • 1
    `why "static" variables cannot be used in non "static" methods?` That's wrong. Static variables and methods **can** be used in non-static context, non-static variables and methods **cannot** be used in a static context. – BackSlash Oct 25 '16 at 19:56
  • This: `public void Person (String name, int age)` is not a constructor. It is just an ordinary method that happens to have the same name as the class. Constructors have no return type! To create a constructor you need to write `public Person (String name, int age)` – Thomas Kläger Oct 25 '16 at 20:25

0 Answers0