如何在java中为特定构造函数创建方法?

时间:2014-02-04 16:42:58

标签: java constructor

当我在Java中创建方法时,无论我使用哪个构造函数来创建该实例,该方法都适用于该类的每个实例。我想知道的是,如何只能由我选择的特定构造函数创建的实例调用方法。

/** (that program below is just an example of my point) */
public class Person{
        private int height;

        /** first constructor */
        public Person(){
            height = 0;
        }

        /** second constructor */
        public Person(int height){
            this.height = height;
        }

        /** I want this method to work just on the constructor with the int parameter   */
        public void getTaller(){
             height = height + 1;
        }

}

5 个答案:

答案 0 :(得分:1)

最接近您要求的是继承和工厂方法:

public class Person {
    public static Person createWithoutHeight() {
        return new Person();
    }

    public static Person createWithHeight(int height) {
        return new PersonWithHeight(height);
    }
}

public class PersonWithHeight extends Person {
    private int height;

    public PersonWithHeight(int height) {
        this.height = height;
    }

    public void makeTaller() {
        height++;
    }
}

答案 1 :(得分:0)

在Java中没有这样的东西,你不能创建一个方法并为特定的构造函数选择这个方法。

答案 2 :(得分:0)

无论使用哪种构造函数,都不能限制实例上方法的使用。 了解实例是什么。 getTaller只会增加从0开始或指定高度开始的高度。

答案 3 :(得分:0)

将类拆分为抽象类和两个实现:

public abstract class Person {
    protected int height;
    protected Person(int height) {
        this.height = height
    }
    public int getHeight() {
        return height;
    }
}

public class PersonImmutable extends Person {
    public PersonFixed(int initialHeight) {
        super(initialHeight)
    }
}

public class PersonMutable extends Person {
    public PersonFixed(int initialHeight) {
        super(initialHeight)
    }
    public void setHeight(int newHeight) {
        this.height = newHeight;
    }
}

答案 4 :(得分:0)

我相信OP正在尝试将函数指针作为参数添加到构造函数中。不幸的是,与C / C ++不同,Java 不允许这样的事情,因为Java中没有函数指针这样的东西。

另一方面,您可以使用轻型命令模式,也就是说,通过对象封装函数。

示例:

class Function {
    // fields here, each stands for a function parameter
    public Function ( insert params here ) {
        // initialize your Function object here
    }

    // the meat of it
    public void execute() {
        // do whatever your function should do
    }
}

然后在构造函数中,将Function作为参数添加到其中,如

public Person(Function myFunction) {
    // do whatever you want here
    // ...
    // then you call your custom function
    myFunction.execute();
}

这是将函数作为参数传递给另一个函数的最通用行为。当然,您可以根据内容调整此内容(向execute()方法添加参数等)。