In Java, is there a legitimate reason to call a non-final method from a class constructor?

前端 未结 5 636
北荒
北荒 2020-12-03 14:56

I recently spent quite a few minutes debugging a problem in production code that in the end turned out to be caused by a class calling an abstract method in its constructor,

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 15:18

    Generally, it's not good design to call methods on a class before it is constructed; however, Java allows exceptions in the case you know what you are doing (ie. you don't access uninitialized fields). With an abstract method, I don't think it is possible to "know" what you're doing in the parent class.

    The above code can easily be solved by imposing stricter interpretation of "a class handles it's responsibilities." It's not the super class's responsibility to initialize the subclass, so it shouldn't be the super class's prerogative to call subclass code before such initialization might be complete.

    Yes, it's done in the JDK (like the HashMap code) with special "init()" methods that imply initialization of all subclass code; but, I would offer that the following pattern of calls is much cleaner and permits more flexibility.

    public class SSCCE {
        static abstract class A {
            public A() {
    
            }
    
            abstract void method();
        }
    
        static class B extends A {
            final String[] arr = new String[] { "foo", "bar" };
    
            public B() {
                super();
                method();
                System.out.println("In B(): " + Arrays.toString(arr));
            }
    
            void method() {
                System.out.println("In method(): " + Arrays.toString(arr));
            }
        }
    
        public static void main(String[] args) {
            new B().method();
        }
    }
    

    it just seems so much cleaner, in so many ways. Failing that, there's always the ability to construct your objects with proper "initialization sequence" through a Factory.

提交回复
热议问题