java - 构造函数重载如何工作

标签 java constructor-overloading

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

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);
        }
    }
}

最佳答案

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

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);
    }
}

关于java - 构造函数重载如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30464463/

相关文章:

java - JAXRS 2.0 客户端 : FOLLOW_REDIRECTS property doesn't work

C++ 类 : Initializing attributes without constructor overloading

C++如何生成函数重载的所有排列?

c++ - std::strings 的 std::initializer_list 的奇怪行为

python - 如何在python中实现多个构造函数?

inheritance - F# 添加多个调用基类构造函数的构造函数重载

java - 将米格布局移植到代号一 适应边距的正确方法是什么?

Java 泛型 : why does this nested template fail?

java - 在 Java 中将二维整数数组显示为图像

java - 在 MATLAB 中监听 Java 自定义事件