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

    // static variable (shared by all instances): global population
    // note: a static variable that changes is bad style for this course,
    // but it is illustrative for this example
    private static int population = 0; // initial value is zero
        
    private int age;     // instance variable: age of this person
    private String name; // instance variable: name of this person 

    // constructor
    public Person(int a, String n) { 
        age = a;      // copy constructor arg to instance var
        name = n;     // copy constructor arg to instance var
        population++; // increase static counter
    }

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

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

    // instance method: return name and age
    // 
    public String toString() { 
        return "Name: " + name + " Age: " + age; 
    }
    
    public static void main(String[] args) {
    	// calling a static method using class name and dot
        // what is the output?
        Person.printPop();     
                          
        // how many instances does this construct?
        Person myMom = new Person(33, "Donna");
        Person myAunt = new Person(44, "Judy");
        Person myChauffeur = myMom;

	// calling an instance method using instance name and dot
        // what is the output?
        myAunt.printName();

	// calling an instance method implicitly
        // what is the output?
        System.out.println(myMom);     
                   
        // calling a static method without class name
	// (uses Person, the containing class, by default)
	// what is the output?
        printPop();
    }
}