Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create methods to a specific constructor in java?

When I create a method in Java, that method applies to every instance of the class, no matter which constructor I use to create that instance. What I want to know is how can I a method be invoked only by instances created by a specific constructor of my choosing.

/** (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;
        }

}
like image 977
user2860452 Avatar asked Dec 02 '25 01:12

user2860452


1 Answers

The closest to what you're asking is inheritance and factory methods:

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++;
    }
}
like image 111
JB Nizet Avatar answered Dec 03 '25 15:12

JB Nizet