The option that best explains why the code segment does not work as expected is option E. The code segment will compile, but the instance variables will not be initialized correctly because the variable names firstName, lastName, and age refer to the local variables inside the constructor.
The reason for the above is that the code statements inside the constructor simply create new local variables with the same names as the instance variables. These local variables are not assigned to the instance variables, so the instance variables remain uninitialized.
So, In the constructor of the Student class, the parameter names are the same as the instance variable names. When you use firstName = firstName;, lastName = lastName;, and age = age;, it refers to the local parameters rather than initializing the instance variables.
See correct text below
Consider the following class declaration.
public class Student
{
private String firstName;
private String lastName;
private int age;
public Student(String firstName, String lastName, int age)
{
firstName = firstName;
lastName = lastName;
age = age;
}
public String toString()
{
return firstName + " " + lastName;
}
}
The following code segment appears in a method in a class other than Student. It is intended to create a Student object and then to print the first name and last name associated with that object.
Student s = new Student("Priya", "Banerjee", -1);
System.out.println(s);
Which of the following best explains why the code segment does not work as expected?
A.
The code segment will not compile because an object cannot be passed as a parameter in a call to println.
B.
The code segment will not compile because firstName, lastName, and age are names of instance variables and cannot be used as parameter names in the constructor.
C.
The code segment will not compile because the constructor needs to ensure that age is not negative.
D.
The code segment will compile, but the instance variables will not be initialized correctly because the variable names firstName, lastName, and age refer to the instance variables inside the constructor.
E.
The code segment will compile, but the instance variables will not be initialized correctly because the variable names firstName, lastName, and age refer to the local variables inside the constructor.