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?
- a local variable defined by any method
- a private instance variable
- a public instance variable
- 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).