/******************************************************************************\ * Name: * Login: * Precept: * * Description: * - 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 * * Dependencies: StdOut.java \******************************************************************************/ public class Person { // static variable: number of people private static int population = 0; // static variables are shared by all instances of a class // note: static (non-constant) variables are considered bad style // for this course, but it is illustrative for this example 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 (cannot access instance variables) 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-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-dot // what is the output? myAunt.printName(); // calling an instance method implicitly // what is the output? StdOut.println(myMom); // calling a static method without class name // (uses Person, the containing class, by default) // what is the output? printPop(); } }