24.8k views
2 votes
Consider the following class definition.

public class Person {
private String name; /* missing constructor */
}
The statement below, which is located in a method in a different class, creates a new Person object with its attribute name initialized to "Washington". Person p = new Person("Washington");

Which of the following can be used to replace /* missing constructor */ so that the object p is correctly created?

A)
private Person()
{
name = n;
}
B)
private Person(String n)
{
name = n;
}
C)
public Person()
{
name = n;
}
D)
public Person(String n)
{
name = n;
}
E)
public Person(String name)
{
String n = name;
}

1 Answer

4 votes

Answer:

The correct answer to this question is "Option D".

Step-by-step explanation:

In the given code, a class "Person" is declared, inside the class a private string variable is declared, in this a parameterized constructor person is declared, that accepts a string value "n" as its parameter, and inside the constructor, name variable holds parameters value, and incorrect choices can be described as follows:

  • Option A and Option C both were wrong because of it a default constructor.
  • In option B, It is incorrect, because it is using a private access modifier.
  • In option E, In the constructor parameter, a string variable name is passed, that is wrong.
User Blerta
by
4.8k points