Machine-translated by Google. Questions are authored in English.
Top

Discussion

The program is run with java -ea Sample73 - what will be the output?

public class Sample73
{
    static class Base { String name() { return "base"; } }
    static class Sub extends Base { String name() { return "sub"; } }

    public static void main(String[] args)
    {
        Base b = new Sub();
        assert b.name().equals("base");
        System.out.println(b.name());
    }
}

  • A.An AssertionError is thrown.
  • B.The program prints sub
  • C.Compilation fails: name() is not visible in Base.
  • D.The program prints base

Answer: A

The variable's declared type is Base but the object is a Sub, and instance methods dispatch on the runtime type. b.name() therefore returns sub, the assertion comparing it to base is false, and an AssertionError is thrown before the print.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.