The Sysadmin Notebook  

Sitemap

Java Classes

Building Java Applications from Class files

Java applications are built from class files. A class definition begins with the keyword 'class' followed by the name of the class and a block that defines methods and variables for the class.

class Robot 
{

	String model;

	void speak (String s) {
		System.out.println("Robot " + model + " says: " + s);
	}



	public static void main (String [] args) {
		Robot r = new Robot();
		Robot p = new Robot();
		r.model = "ZX4RV";
		p.model = "23LMT";
		p.speak("This is p speaking");
		r.speak("This is r speaking");
	}
}	

Besides the main method, this class defines one instance variable and one instance method. Objects of the class are created using the 'new' operator which calls the objects constructor.

Instance variables belong to particular instances of the class, whereas static variables belong to the class.

class Robot 
{

	static int population = 0;
	String model;

	Robot () {
		population++; 
	}

	void speak (String s) {
		System.out.println("Robot " + model + " says: " + s);
	}



	public static void main (String [] args) {
		Robot r = new Robot();
		Robot p = new Robot();
		r.model = "ZX4RV";
		p.model = "23LMT";
		r.speak("This is r speaking");
		p.speak("This is p speaking");
		System.out.println("Total Robot population: " + population);
	}
}	

To create an object of the class a special method must be defined in the class declaration that has the same name as the class but no return value: