Why instance variables get initialized before constructor called?

后端 未结 2 1703
野趣味
野趣味 2020-12-14 09:56

I have this following piece of code:

public abstract class UCMService{
    private String service;     

    protected DataMap dataMap = new DataMap(); 

            


        
2条回答
  •  粉色の甜心
    2020-12-14 10:34

    Short answer:
    Because the spec says so.

    Long answer:
    It would be very strange for the constructor to be unable to use inline-initialized fields.

    You want to be able to write

    SomeService myService = new SomeService();
    public MyConstructor() {
        someService.doSomething();
    }
    

提交回复
热议问题