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

Discussion

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

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

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

  • A.An AssertionError is thrown.
  • B.Compilation fails.
  • C.The program prints base
  • D.The program prints sub

Answer: D

Static methods are hidden rather than overridden and are resolved against the type named at the call site. Base.who() is base, so the assertion passes, and Sub.who() is sub, which is printed. There is no runtime dispatch for static methods.

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

Post your comment

Please log in or register to post a comment.