Java Reference
In-Depth Information
Note Aclassthatisdeclared public mustbestoredinafilewiththesamename.
Forexample,a public Image classmustbestoredin .Asourcefile
can declare one public class only.
Youwilloftendeclareyourclass'sinstancefieldstobe private andprovidespecial
public instancemethodsforsettingandgettingtheirvalues.Byconvention,methods
thatsetfieldvalueshavenamesstartingwith set andareknownas setters .Similarly,
methodsthatgetfieldvalueshavenameswith get (or is ,forBooleanfields)prefixes
and are known as getters . Listing 2-13 demonstrates this pattern in the context of an
Employee class declaration.
Listing 2-13. Separation of interface from implementation
public class Employee
private String name;
public Employee(String name)
public void setName(String empName)
name = empName; // Assign the empName argument to the
name field.
public String getName()
return name;
Listing 2-13 presents an interface consisting of the public Employee class, its
public constructor,andits public setter/gettermethods.Thisclassandthesemem-
bers can be accessed from anywhere. The implementation consists of the private
name fieldandconstructor/methodcode,whichisonlyaccessiblewithinthe Employ-
ee class.
Search WWH ::

Custom Search