Static Variables and Methods

AP Computer Science A· difficulty 3/5

public class Money {
    private int cents;
    private Money(int c) { cents = c; }
    public static Money fromDollars(int d) {
        return new Money(d * 100);
    }
    public int getCents() { return cents; }
}
// ...
Money m = Money.fromDollars(3);
System.out.println(m.getCents());

What is printed?

  • A

    3

  • B

    100

  • C

    Compile-time error

  • D

    300

    check_circle

Explanation

The static factory invokes the private constructor with 300, which is stored in cents.

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

Related questions