This book is now obsolete Please use CSAwesome instead.
2.5. An Object Oriented Class Example¶
Let’s create a class where each object of the class represents a person. Every person has a name and a cell phone number which we will store in String variables. A string is a sequence of characters like in “Hello”. We can store the name and cell phone number in fields in a Person object. We provide methods to get and set the data. We provide a constructor to initialize the data when the object is first created.
Go ahead and click the button to see what gets printed.
Note
A class declaration typically starts with public
then class
then the name of the class. The body of the class is defined inside a {
and a }
.
Check Your Understanding
A person’s name can actually be broken into parts. We can create a name class to handle this.
public class Name { private String first; private String last; public Name(String theFirst, String theLast) first = theFirst; last = theLast; } public void setFirst(String theFirst) first = theFirst; } public void setLast(String theLast) first = theLast; } }
public class PhoneNumber { private String country; private String areaCode private String number public PhoneNumber(String theCountry, theArea, theNumber) country = theCountry; areaCode = theArea; number = theNumber; } public String getNumber() { return number; public void setNumber(String theNumber) number = theNumber; } }