A Quick and Dirty Intro to Classes in Java - Part 2

Basic Mechanics

Classes Classes as Types

Objects (Instances)

Creating Objects of a Class Constructors - Initializing Objects Default Constructors and Constructors with Arguments this Overloading A fully Specified class
public class Counter {
	public Counter() {val = 0;}		
	
	public void up() {val++;}
	public void down() {val--;}
	public int get() {return val;}
	
	public String toString() {return val+"";}
	
	private int val;
}
	

Notes:

Adding a main Method

A main method is often added to a class whose execution will either 'show-off' the behavior of the class, or test the class (basically the same thing).

public class Counter {
	public Counter() {val = 0;}		
	
	public void up() {val++;}
	public void down() {val--;}
	public int get() {return val;}
	
	public String toString() {return val+"";}	// The String concat, '+', converts integers to String automatically
	
	private int val;
	
	public static void main(String [] args) {
		Counter c = new Counter();
		System.out.println("After initialization: " + c.get());
		System.out.println("After initialization, using toString():" + c.toString());
		// The String concat, '+', calls an object's toString automatically
		System.out.println("After initialization, using toString() implicitly: " + c);
		
		System.out.println("going up!");
		for (int i = 0; i < 10; i++) {
			c.up();
			System.out.println("The counter after " + i + " up(s) is now: " + c);
		}
		
		System.out.println("down we go!");
		for (int i = 0; i < 10; i++) {
			c.down();
			System.out.println("The counter after " + i + " down(s) is now: " + c);
		}
	}
}
	

Simple Class Design

A PowerPoint on Basic Class Design