Structure of a class: Person

public class Person {
    private int age;

    // constructor. Is called when a new object is created
    public Person(int theAge) {
	age = theAge;
    }

    public int getAge() {
	return age;
    }

    public void yearPassed() {
	age++;
    }

    public boolean canDrive() {
	if (age < 16) {
	    return false;
	} else {
	    return true;
	}
    }
}


Testing a class

// this is a testing class for the class person

public class testPerson {
    public static void main(String [] args) {
	Person jane = new Person(14);
	Person joe = new Person(15);

	System.out.println("Jane is " + jane.getAge() + " old");
	System.out.println("Joe is " + joe.getAge() + " old");
	if (jane.canDrive()) {
	    System.out.println("Jane can drive");
	}
	if (joe.canDrive()) {
	    System.out.println("Joe can drive");
	}

	jane.yearPassed();
	joe.yearPassed();

	System.out.println("Jane is " + jane.getAge() + " old");
	System.out.println("Joe is " + joe.getAge() + " old");

	if (jane.canDrive()) {
	    System.out.println("Jane can drive");
	}
	if (joe.canDrive()) {
	    System.out.println("Joe can drive");
	}

    }
}

This is an example from CSci 2101 course.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.