Java Reference
In-Depth Information
Suppose you want to represent real-world people in your program. You will create a Person class and its instances
will represent people in your program. The Person class can be defined as shown in Listing 1-1. This example uses the
syntax of the Java programming language. You do not need to understand the syntax used in the programs that you are
writing at this point; I will discuss the syntax to define classes and create objects in subsequent chapters.
Listing 1-1. The Definition of a Person Class Whose Instances Represent Real-World Persons in a Program
package com.jdojo.concepts;
public class Person {
private String name;
private String gender;
public Person(String initialName, String initialGender) {
name = initialName;
gender = initialGender;
}
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
public String getGender() {
return gender;
}
}
The Person class includes three things:
name and gender .
Two instance variables:
Person(String initialName, String initialGender)
One constructor:
getName() , setName(String newName) , and getGender()
Three methods:
Instance variables store internal data for an object. The value of each instance variable represents the value of a
corresponding property of the object. Each instance of the Person class will have a copy of name and gender data. The
values of all properties of an object at a point in time (stored in instance variables) collectively define the state of the
object at that time. In the real world, a person possesses many properties, for example, name, gender, height, weight,
hair color, addresses, phone numbers, etc. However, when you model the real-world person using a class, you include
only those properties of the person that are relevant to the system being modeled. For this current demonstration, let's
model only two properties, name and gender , of a real-world person as two instance variables in the Person class.
A class contains the definition (or blueprint) of objects. There needs to be a way to construct (to create or to
instantiate) objects of a class. An object also needs to have the initial values for its properties that will determine its
initial state at the time of its creation. A constructor of a class is used to create an object of that class. A class can have
many constructors to facilitate the creation of its objects with different initial states. The Person class provides one
constructor, which lets you create its object by specifying the initial values for name and gender . The following snippet
of code creates two objects of the Person class:
Person john = new Person("John Jacobs", "Male");
Person donna = new Person("Donna Duncan", "Female");
Search WWH ::




Custom Search