构造函数重载的工作原理

时间:2015-05-26 16:49:09

标签: java constructor-overloading

如果我无法修改Factory.create方法(只能修改Task.<init>(SubType)Factory.create类),如何让Task调用SubType构造函数?< / p>

public class Test {

    public static void main(String[] args) {
        Factory.create(new SubType());
        // OUTPUT:
        // task instanceof SubType: true
        // callable  (PROBLEM: I want SubType constructor to be invoked)
    }

    public static class SubType implements Callable {
        @Override
        public Object call() throws Exception {
            return null;
        }
    }

    public static class Task {
        private Callable callable;
        private SubType subType;

        public Task(SubType subType) {
            System.out.println("Subtype");
            this.subType = subType;
        }
        public Task(Callable callable) {
            System.out.println("callable");
            this.callable = callable;
        }
    }

    public static class Factory {

        // If change method argument type to SubType it will invoke 
        // Task.<init>(SubType) constructor, but I can't modify it
        public static Task create(Callable task) {
            System.out.println("task instanceof SubType: " + (task instanceof SubType));
            return new Task(task);
        }
    }
}

2 个答案:

答案 0 :(得分:3)

Task类上创建一个公共工厂静态方法,并将构造函数设为私有或包私有

public static class Task {
    private Callable callable;
    private SubType subType;

    private Task(SubType subType) {
        System.out.println("Subtype");
        this.subType = subType;
    }
    private Task(Callable callable) {
        System.out.println("callable");
        this.callable = callable;
    }

    public static Task create ( final Callable callable )
    {
       if ( callable instance of SubTask )
       {
         return new Task( (SubType) callable );
       }

       return new Task( callable );

    }
}

public static class Factory {

    // Note that we are now calling Task's factory method
    public static Task create(Callable task) {
        System.out.println("task instanceof SubType: " + (task instanceof SubType));
        return Task.create(task);
    }
}

答案 1 :(得分:2)

调用哪个重载方法或构造函数的选择是在编译时根据参数的声明的类型完成的。因此,即使getClass().getClassLoader().getResourceAsStream("resources/"+docLocation的实际具体类型为task,其声明的类型为SubType,第二个构造函数,将Callable作为参数,将始终被调用。

因此,如果你想在使用SubType构造Task时发生不同的事情,那么你应该在Task构造函数中测试Callable的类型:

Callable