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

Discussion

Which line rests on a mistaken assumption?

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

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

  • A.System.out.println(b.who());
  • B.Every line above is correct as written.
  • C.assert b.who().equals("base") : b.who();
  • D.Base b = new Sub();

Answer: C

Instance methods dispatch on the runtime type, so b.who() returns sub even though the variable is declared Base. The assertion assumes the declared type decides, which is only true for static methods and fields. It therefore fails on entirely correct polymorphism.

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

Post your comment

Please log in or register to post a comment.