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;
}
}
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++;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With