Why can't I use a try block around my super() call?

前端 未结 0 1037
花落未央
花落未央 2021-02-11 13:35

So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor. What I want to know is

相关标签:
回答
  • 2021-02-11 14:03

    Unfortunately, compilers can't work on theoretical principles, and even though you may know that it is safe in your case, if they allowed it, it would have to be safe for all cases.

    In other words, the compiler isn't stopping just you, it's stopping everyone, including all those that don't know that it is unsafe and needs special handling. There are probably other reasons for this as well, as all languages usually have ways to do unsafe things if one knows how to deal with them.

    In C# .NET there are similar provisions, and the only way to declare a constructor that calls a base constructor is this:

    public ClassName(...) : base(...)
    

    in doing so, the base constructor will be called before the body of the constructor, and you cannot change this order.

    0 讨论(0)
  • 消灭零回复
提交回复
热议问题