Index

Overview


This section gives examples of methods that are common to most classes, so you will be implementing (and using) these a lot.

Object Equality


See equals

Getters


What Is A Getter?
The purpose of a getter method is to "get" the ivar value from the object and return it.
Example
Here we have a class with three ivars.
public class City {

	private String name;
	private String stateAbbrev;
	private String zip;
Getters
And here are the getters -- one for each ivar.
public String getName()  {
	return this.name;
}

public String getStateAbbrev()  {
	return this.stateAbbrev;
}

public String getZip()  {
	return this.zip;
}


Setters


What Is A Setter?
The purpose of a setter method is to receive a method parameter value and "set" it (assign it) to an ivar.
Example
Here we have a class with three ivars.
public class City {

	private String name;
	private String stateAbbrev;
	private String zip;
Setters
And here are the setters -- one for each ivar.
public void setName(String nm)  {
	this.name = nm;
}

public void setStateAbbrev(String abbr)  {
	this.stateAbbrev = abbr;
}

public void setZip(String z)  {
	this.zip = z;
}


Copy Constructor


Example
Here is an example implementation of a copy constructor.
public City(String name, String stateAbbrev, String zip) {
	this.name = name;
	this.stateAbbrev = stateAbbrev;
	this.zip = zip;
}

//When you want a copy and want to preserve the original
public City(City source) {
	this(source.getName(), source.getStateAbbrev(), source.getZip());
}

//end constructors
Using A Copy Constructor
City copy = new City(city1);

Using A Copy Constructor On A List
List<Integer> original = new ArrayList<>();
original.add(5);
List<Integer> copy = new ArrayList<>(original);