Accessor Methods

AP Computer Science A· difficulty 1/5

public class Student {
    private String name;
    public Student(String n) { name = n; }
    public String getName() { return name; }
}
// ...
Student s = new Student("Ana");
System.out.println(s.getName());

What is printed?

  • A

    Compile-time error

  • B

    null

  • C

    name

  • D

    Ana

    check_circle

Explanation

The accessor method getName returns the instance variable name, which was set to "Ana" by the constructor.

Want 10 more like this — adaptive to your weak spots?

Related questions