Given
public enum Title {
MR("Mr."), MRS("Mrs."), MS("Ms.");
private final String title;
private Title(String t) {
title = t;
}
public String format(String last, String first) {
return title + "" + first + "" + last;
}
}
public static void main(String[] args){
System.out.println(Title.MR.format("Doe","John"));
}
Does anyone know how to explain this ? Keep in mind the code is not fully complete. This happens to be a question from a book. The Answer to this question is Mr. John Doe.
Thanks
Well, first of all, consider reading this, in order to understand what is an
Enum, how it works, and when you should use it.Now, concerning your
Enumexample, you are declaring anEnumerated type with three possible values:MR,MRS, andMS.Enums, just likeClasses, can have methods and constructors. In your example,Titlehas a single argument constructor — which stores a description of theTitle–, and a method that basically prepends the description to a given name — theformatmethod.So, when you invoke
Title.MR.format("Doe","John")), first you get an instance of theMRTitle, and then you invoke theformatmethod, which returnsMr.John Doe.Also note that only one instance of each
Titleis created, so that invokingTitle.MRseveral times will always return the same objet.