Are fields initialized before constructor code is run in Java?

后端 未结 5 2209
梦谈多话
梦谈多话 2020-11-22 06:39

Can anyone explain the output of following program? I thought constructors are initialized before instance variables. So I was expecting the output to be \"XZYY\".



        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 07:29

    When you invoke a constructor, the instance variable initializers run before the body of the constructor. What do you think the output of the below program ?

    public class Tester {
        private Tester internalInstance = new Tester();
        public Tester() throws Exception {
            throw new Exception("Boom");
        }
        public static void main(String[] args) {
            try {
                Tester b = new Tester();
                System.out.println("Eye-Opener!");
            } catch (Exception ex) {
                System.out.println("Exception catched");
            }
        }
    }
    

    The main method invokes the Tester constructor, which throws an exception. You might expect the catch clause to catch this exception and print Exception catched. But if you tried running it, you found that it does nothing of that sort and It throws a StackOverflowError.

提交回复
热议问题