Constructors

AP Computer Science A· difficulty 3/5

public class Demo {
    private int x = 10;
    private int y;
    public Demo() {
        y = x + 5;
    }
    public int sum() { return x + y; }
}
// ...
Demo d = new Demo();
System.out.println(d.sum());

What is printed?

  • A

    15

  • B

    25

    check_circle
  • C

    10

  • D

    5

Explanation

x is initialized to 10 before the constructor body runs; then y becomes 15; sum returns 25.

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

Related questions