Search code examples
javaoopconstructoraccess-modifiers

Which variables constructor can access in Java class?


I am studying constructors in Java (OOP) but couldn't figure it out that what type of variables constructor can access? Which of the following variables could be accessed by constructor?

  1. a local variable defined by any method
  2. a private instance variable
  3. a public instance variable
  4. a static variable

I created following example to elaborate my question:

public class constructorAccess {
    public int marks; // 3. Public instance variable
    private String firstName; // 2. Private instance variable
    static final String LASTNAME = "Smith"; // 4. Static variable

    public static void studentId(){
        int id; // 1. Local variable inside method
        id = 5;
        System.out.println(id);
    }

    public constructorAccess(int marks, String firstName) {
        this.marks = marks;
        this.firstName = firstName;
    }
}

Is it possible to access id(1. Local variable declared in the studentId method) and LASTNAME (4. static variable declared in the class) from constructorAccess?

public constructorAccess(int marks, String firstName) {
   this.marks = marks;
   this.firstName = firstName;
   // How can I use id variable here from studentId method?
   // How can I use LASTNAME static variable here?
}

I accessed the private and public instance variables with this. to reference but the LASTNAME and id variables give me error (create a local variable).


Solution

  • Local variables are accessible only to code inside the scope (i.e., the pair of {...}) where the local variable is declared. It wouldn't make sense to access them from outside the method, because the existence of local variables is tied to a particular method call: while the method is not currently being executed, its local variables don't exist at all; and if the method calls itself recursively or it is being executed from multiple threads, every method call has its own independent set of local variables.

    To your other three questions: Yes, constructors (and methods) can always access any instance and static variables if they are declared in the same class. If they are in different classes, then more complex access rules come in to play.

    If you received an error in your example assigning to LASTNAME that is because you declared it final, meaning that the variable can only be assigned to exactly once, and since its value is already assigned, you can't assign to it again. But it is still "accessible" because you can read its value. Or make it static non-final, and then you can both read and assign to it.