Person.java


Below is the syntax highlighted version of Person.java.


/****
 * Person.java:
 * - simulates a person (not in the Terminator/Blade Runner sense)
 * - demonstrates defining static/non-static fields and methods
 * - demonstrates calling these methods with two different syntaxes
 ***/
public class Person { // definitions of fields and methods go here
    
    private int age;     // instance variable: age of this person
    private String name; // instance variable: name of this person 

    // static variable (shared by all instances): global population
    private static int population = 0; // initial value is zero
    // note: a static variable that changes is bad style for this course,
    // but it is illustrative for this example
    
    public Person(int a, String n) { // constructor
        age = a;  // copy constructor arg to instance var
        name = n; // copy constructor arg to instance var
        population++; // increase static counter
    }

    public static void printPop() { // static method (not per-instance)
        StdOut.println("The population is " + population);
    }

    public void printName() { // instance method
        StdOut.println("My name is " + name + ".");
    }

    public void printInfo() { // instance method: print age and name
        StdOut.print("My age is " + age + ". "); 
	printName(); // call method on this instance without period
    }
    
    public static void main(String[] args) {
    	// calling a static method using class name and period
        // what is the output?
        Person.printPop();     
                          
        // how many instances does this construct?
        Person myMom = new Person(33, "Pandora");
        Person myUncle = new Person(44, "Lucius");
        Person myDentist = myMom;

	// calling an instance method using instance name and period
        // what is the output?
        myDentist.printInfo();     
                   
        // calling a static method without a period
	// (uses Person, the containing class, by default)
	// what is the output?
        printPop();
    }
}