Lesson 2 - Classes

TABLE OF CONTENTS: Introduction - Object-Oriented Programming - The main method - Varaibles - Methods - Constructors - API

Introduction -

Classes are the basic building block of Java (OOP). You have already written a class in lesson 1 when you created the HelloWorld class. However, in that lesson you were just copying code to get started. After this lesson, you will have an understanding of how to organize, design and write classes from scratch by yourself.

Pre-requisites -

Before beginning this lesson you should have completed the HelloWorld2 program.  (This would give you experience using the programming environment and structuring simple programs.) 

Goals -

  1. Students will understand the basic concepts of object oriented programming.
  2. Students will be able to divide a programming task into classes and methods to create an organized solution. 
  3. Students will be able to use variables to store and access data within a program.
  4. Students will be able to use the Java API documentation to find and utilize classes and methods in the Java library.

Section 1: Object-Oriented Programming

These are your objectives for this section:

After reading this section, you will be able to explain the differences between classes and objects.

After reading this section, you will be able to explain the differences between sequential and object-oriented programming.

Given a description of a program, be able to identify objects that are needed to accomplish that task.

Java is an object-oriented programming (OOP) language. The concept of OOP allows programs to have many different elements that all interact with each other. While you are new to the term, you have you object-oriented programs all your life on the computer. Windows applications are almost always object-oriented. The browser window you are using right now is full of objects. The buttons, the menus, the slide bars, the minimize-maximize buttons, the main window (which is also full of objects.)... Object oriented programming takes complex things and programs all of the pieces separately and then teaches the objects how to interact with each other. This allows objects to be used over and over in many different ways. Objects can be simple or complex. They can be graphical (visual) or more analytical (for processing.)

The basic builging block of the Java language is a class. A class defines a 'class' of objects. It is the blueprint to be used whenever an object is created. The code you put into a class will include what data the object will keep track of and what functions it can perform. You've already written your first class. The HelloWorld class from Lesson1 defined a class of objects that said Hello to the computing world.

If we think of a Person as an object. We could write the Person class which defines that class of objects.

A Person would have a name, height, age, eye color, and many other parameters that might make it different from other objects created from the Person class. Also a Person would have many methods (or functions) that it can perform: sayName, walk, sit, turn, and many, many others... Think of yourself as a Person object that might be controlled by a program. What would you put into the program?

Section 2: The main method

This is your objective for this section:

After reading this section, you will be able to explain the significance of the main method in Java programs.

In Lesson1 you were able to compile and run this program.

// My first program!!!

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }

Let's analyze what it really means.

public class HelloWorld

This first line says that you are declaring a class of objects called HelloWorld. The class is public meaning there are no restrictions on who can access it. (Later we will learn the difference between private and public, but I bet you can figure it out on your own.) This class will contain the blueprint for all HelloWorld objects.


The curly brackets group the code that is within the class. They are always used for grouping sections of code together.

 public static void main(String[] args) 

The HelloWorld class is very simple and it only contains one method - the main method. The syntax for starting a main method is always the same. Including a main method in our program allows the program to be run as an application.

 System.out.println("Hello World!"); 

This line uses the System.out object (which is connected to the terminal display) and runs the println method. This prints out the text of HelloWorld.

Section 3: Variables

These are your objectives for this section:

Given a list of identifiers, students will be able to determine which ones are valid.

Given a description of a variable, students will be use the correct syntax to declare and initialize it.


Java, like most other programming languages is very algebraic. It works with variables, and those variables have names. Rather than using single letter variables (which aren't very descriptive) it is good practice to use words as variable names in your programs. The name of a variable is refered to as an identifier. There are only a few rules that apply to choosing identifier names:

All of these would be valid identifiers:


While these are invalid:

1stPlace  //starts with a number!

two words //can't have a space!

Real*Cool //can't have special symbols!

Types of variables

Every variable must have a type. There are some primitive types that we will use. These primitive types are only used to store simple numerical values. Some of the primitive types are listed below.

Type Description
int Integer numbers
double Decimal numbers
boolean True/False values
char Single characters

We will also use variables to represent instances of classes. (Variable names are given to objects.) A few that we have (or soon will) used are listed in the table below, however any class you write can be used to make objects.

Type Description
String Text values
Random Random number generator objects
Scanner Scanner objects (used to read input)
Turtle Drawing objects (from Java Au Naturel)

Declarations and Assignment statements

Declaring a variable gives it definition so that the compiler knows what it is. Often when we declare a variable we also assign it a value.

int number; //just a declaration
number = 15; //The left side ALWAYS is the variable you are changing. 
int number = 15; // Declaring and assigning a value in one step!
String name = "Sarah";
double decimal = 2.71828;

Section 4: Methods

These are your objectives for this section:

Given a method header, students will be able to identify the name of the method, the return type, and the paramters (inputs) to the method.

Given a description, student will use the correct syntax to write a method header that meets the description.

Given a larger scale task, students will be able to break the task into methods to organize the code.

Methods define the actions that an object can do.

Methods are also useful in organizing your code, whenever you have an action that will need to be performed many times, make it a method. That way you can just call the method many times, rather than writing the code that was in the method over and over. It is another way that we make code re-usable!

The syntax for a method (which must be within a class) is:

scope returnType methodName ( parameters )
	lots of code...

It's really the first line that we will concentrate on at first - the method header. This line defineshow the method interacts with other parts of the program.

public void sayHello(String name)
	System.out.println("Hello, "+name);

This is a method that says "Hello" to someone. It recieves one String (called name) and returns nothing (void).

public int total(int num1, int num2, int num3)
	int result = num1+num2+num3;
	return result;

This method recieves three numbers and returns an integer. The method name is total, which is appropriate since it adds the numbers up.

public String getName()
	Scanner keyboard = new Scanner(System.in);
	System.out.println("Please enter your name.");
	String input = keyboard.next();
	return input;

This method gets the user's name and returns it as a String. It recieves no parameters.


Try some example coding challenges below. You can check your work by highlighting the answer section.

method header method name return type input parameters
public void connect( )
void (nothing)
empty (none)
public int sum(int a, int b)
two integers (named a & b)
public String getName( )
empty (none)
public static void main(String[] args)
String array (named args)
public boolean isGameOver(int score)
boolean (T/F)
one integer (named score)


Section 5: Constructors

This is your objective for this section:

After reading this section, students will be able to write and use constructor methods to initialize objects.

There is one special case of a method that doesn't quite follow the rules of the previous section. A constructor is a method that is only called when a new object is created. The constructor method in a class allows things to be initialized before the object is ever used.

For example, in a Person class...

public class Person

	int myAge;
	String myName;

	public Person(String name)
		myName = name;
		myAge = 0;

	public void sayName()
		System.out.println("My name is "+myName);


The Person class also has a constructor method. This method is different from other methods in these ways:

In another program that uses Person objects, the code to create a Person you would use this line:

Person spock = new Person("Mike");

Extra resources: API (The Java library)

This is your objective for this section:

Given access to the API documentation, students will be able to find classes and methods in those classes to use as tools within their programs.

After reading this section, students will be able to use import statements and library functions as tools in their programs.

There are many classes that have already been created for you to use. You can find them all in the Java API. This is essentially a library of Java classes that you can use. You could program for years and not use all of them! For many of the classes in the library, you will need to use an import statement at the top of your program to tell the compiler to import that class from the library.

import java.util.Random;

public class LuckyNumber
	public static void main(String[] args)
		Random randy = new Random();
		int lucky = randy.nextInt(100);
		System.out.println("Your lucky number is "+lucky);


Here are a few programming challenges for you to try:

(This assignment is worth 90 points. You must complete each of the following programs)

  1. Complete the Turtle exercises in unit 2 of Java Au Naturel. These provide an excellent way to practice working with objects and classes (and graphics!)
  2. Write a program that uses a Random object to display a random decimal between 0 and 1 (look at the API to find out more about Random objects.)
  3. Write a program that asks the user their name and then changes all of the vowels to numbers i1, a2, e3, o0, u4. (Read about methods in the String class that can help.)

Helpful References


Java Au Naturel

Java API

Online Tutorial - LandOfCode

Online Java Tutorial - Cafe Au Lait

Text - Java Concepts by Cay Horstmann (Chapter 6 - Decisions) *We have six copies of this book in the computer lab*