0

I'm confused as to why I can't denote a variable private when creating it inside a constructor or inside the main but can do it outside those inside the class.

public class Stuff
{
    private double x;

    public Stuff(int i, double d) {
        private double y;
    }

    public static void main(String[] args) {
        private double z;
    }
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243

2 Answers2

5

Access modifiers don't make sense inside functions, because the variables go out of scope immediately after the function ends

Natecat
  • 2,175
  • 1
  • 17
  • 20
2

A class has fields and methods that can be accessed by certain other classes, and always the class itself, depending on the access level modifiers (private, default-access, protected, or public). You can view the fields and methods as the attributes/properties of the class.

A field is what you describe as "a variable in a class that is not inside any method". A field describes a value the class has, and a method describes what the class (or the objects of the class) can do.

Ignoring the static keyword for the simplicity of this post, a class is a template for creating objects. Every object you create of a certain class will have a set of its own fields and methods (unless the field or method is static).

If you set the field of a class to private nothing outside the class can reach it. Only the class itself (essentially meaning the methods of the class) can reach it. Same goes with private methods. Only other methods of the class can reach the private methods.

Consider this example:

public class Person {
    private String name;
    public int id;

    public Person(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }
}

If somebody wanted to acess the name of this person by directly referring to the name, they would not be able to do it, since the name is private. They would have to use the method getName() to do it.

Person person = new Person(John, 5);
System.out.print(person.name); //does not work

Person person = new Person(John, 5);
System.out.print(person.getName()); //works

This is good because if the name was directly accessible, you could write:

person.name = "Felicity";

and change the name of the person, which is not wanted (we can do this with the id, and this could cause troubles). This is not possible when the name is private.

A variable inside a method, however, is not a field. Meaning it is not an attribute of the object. It is simply a temporary variable that exists to allow the method to do what it wants to do. When the method has finished executing, the variable is destroyed. Declaring such a variable as private or anything else is completely meaningless and is therefore not allowed.

RaminS
  • 2,208
  • 4
  • 22
  • 30