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 run button 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.

Click on the class declaration (not the body of the class) in the following class definition. Then click the "Check Me" button to see if you are correct or not.The class declaration starts the class. It contains the keyword class in it.
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;
     }

}
Click on the class declaration (not the body of the class) in the following class definition. Then click the "Check Me" button to see if you are correct or not.The class declaration starts the class. It contains the keyword class in it.
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;
     }

}
Next Section - Running a Java Program