220k views
2 votes
Consider the following declaration for a class that will be used to represent points in the xy-coordinate plane.

public class Point
{
private int x; // x-coordinate of the point
private int y; // y-coordinate of the point

public Point()
{
x = 0;
y = 0;
}

public Point(int a, int b)
{
x = a;
y = b;
}
// Other methods not shown
}

The following incomplete class declaration is intended to extend the above class so that points can be named.

public class NamedPoint extends Point
{
private String name; // name of point
// Constructors go here
// Other methods not shown
}

Consider the following proposed constructors for this class.
I. public NamedPoint()
{
name = "";
}

II. public NamedPoint(int d1, int d2, String pointName)
{
x = d1;
y = d2;
name = pointName;
}

III. public NamedPoint(int d1, int d2, String pointName)
{
super(d1, d2);
name = pointName;
}

Which of these constructors would be legal for the NamedPoint class?

a. I only
b. II only
c. III only
d. I and III only
e. II and III only

1 Answer

4 votes

Final answer:

Constructors I and III are legal for the NamedPoint class. Constructor I relies on the default constructor of the superclass, while Constructor III uses the super keyword to explicitly call the superclass's constructor. Constructor II is illegal because it tries to set private fields directly.

Step-by-step explanation:

The student is asking which constructors would be legal for the NamedPoint class that extends the Point class. The legality of constructors in a Java class is determined by the correct use of the super keyword for calling a superclass's constructor and the proper setting of private fields.

Constructor I sets the name field only, assuming the superclass's no-argument constructor will be called by default to initialize x and y to zero. Constructor III is also correct because it explicitly calls the superclass's constructor with arguments using the super keyword and sets the name field.

Constructor II, however, attempts to set the x and y fields directly, which is not allowed since these fields are declared private in the superclass.

Therefore, the legal constructors are I and III only.

User Phil Gref
by
8.4k points

No related questions found