Say I have a class for Person
which I want to implement as a static factory:
public class Person {
private String name;
private Double heightInMeters;
private Person(String name, Double meters) {
this.name = name;
this.heightInMeters = meters;
}
public static Person fromNameAndCentimeters(String name, Double centimeters) {
return new Person(name, centimeters/100.0);
}
public static Person fromNameAndInches(String name, Double inches) {
return new Person(name, inches/3.28);
}
public string toString() {
return "My name is " + name + " and my height in meters is " + heightInMeters;
}
}
But I also have a nearly identical class Jeff
for which I want to have slightly different factory methods:
public class Jeff {
public static final JEFF_NAME = "Jeff";
private String name = JEFF_NAME;
private Double heightInMeters;
private Jeff(String name, Double meters) {
this.name = name;
this.heightInMeters = meters;
}
public static Jeff fromCentimeters(Double centimeters) {
return new Jeff(name, centimeters/100.0);
}
public static Jeff fromInches(Double inches) {
return new Jeff(name, inches/3.28);
}
public String toString() {
return "My name is " + name + " and my height in meters is " + heightInMeters;
}
}
Clearly, Jeff
and Person
are related, and I want to do something like
public printIntroduction(Object somebody) {
System.out.println(somebody);
}
printIntroduction(Person.fromNameAndInches("Bob", 65))
printIntroduction(Jeff.fromInches(60))
My first thought was to have Jeff
inherit from Person
- but child classes inherit static methods, and I don't want Jeff
to have fromNameAndInches
. What's the best way to go about this?