AP Computer Science A · Topic 5.9
this Keyword Practice
Part of Writing Classes.
Practice questions
10
Sample questions
5 of 10 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
public class Person { private String name; public Person(String name) { name = name; } public String getName() { return name; } } // ... Person p = new Person("Bo"); System.out.println(p.getName());What is printed?
- Acheck_circle
null
- B
Bo
- C
name
- D
Compile-time error
Why
Without this.name = name the assignment only sets the parameter to itself; the instance variable name remains its default null.
- A
Sample 2difficulty 2/5
public class Pair { private int a, b; public Pair(int a, int b) { this.a = a; this.b = b; } public int sum() { return a + b; } } // ... Pair p = new Pair(3, 4); System.out.println(p.sum());What is printed?
- Acheck_circle
7
- B
0
- C
12
- D
Compile-time error
Why
this.a and this.b are set to 3 and 4; sum returns 7.
- A
Sample 3difficulty 3/5
public class Point { private int x, y; public Point(int x, int y) { /* missing */ this.y = y; } }Which line replaces /* missing */?
- A
this.x = this.x;
- B
x = x;
- Ccheck_circle
this.x = x;
- D
x = this.x;
Why
Use this.x to refer to the field shadowed by the parameter; otherwise the assignment is parameter-to-itself.
- A
Sample 4difficulty 3/5
public class Box { private int width; public Box(int width) { width = width; } }What is wrong with the constructor?
- A
Nothing is wrong
- B
private fields cannot be set in a constructor
- Ccheck_circle
The parameter shadows the field; assignment has no effect on the field
- D
Constructors cannot have parameters
Why
The parameter width shadows the instance field of the same name. The assignment width = width copies the parameter to itself; it should be this.width = width.
- A
Sample 5difficulty 3/5
public class A { public A() { System.out.print("hi "); this(5); } public A(int n) {} } // ...What is the result?
- A
Nothing is printed
- B
Run-time error
- Ccheck_circle
Compile-time error: this(...) must be the first statement
- D
hi printed
Why
A call to this(...) (or super(...)) must appear as the very first statement of a constructor.
- A