BFOIT - Introduction to Computer Programming

What's a Class?

Introduction

OK, now that you have mastered the "Edit, Compile, Execute" cycle, it's time to find out what all the stuff is that we surround our simple message "Hello World!" with, to get it displayed.

When we started working with Logo in TG, all we had to do was enter commands and things happened.  But with Java, we had to create a class with a main procedure (called a method in Java).  What's with this???

In this lesson, you will learn

  1. what a class is and its syntax,
  2. what Java's keywords are,
  3. what a method is, and its syntax,
  4. about a special method:
    public static void main(String[] args)

If Java programs are built from things called classes,
what is a class?

A class is a specification (think of it as a blueprint or pattern and a set of instructions) of how to provide some service.  Like a blueprint or a pattern, a Java class has exact specifications.  The specification is the class' contract.  I've talked about contracts before.  First, back when I introduced Adding Commands in Logo and again when we learned about Defining Operators, when we specified a contract for a Grid Toolkit.

Engineers and construction and factory workers use blueprints to build cars, buildings, bridges, virtually anything.  Tailors, seamsters, printers use patterns to make the clothes we wear, books we read.  Chefs follow recipes to put together meals.

Start by thinking of a class as an object.  Imagine a class as a container, like that glass or plastic bottle you drink your favorite beverage from.  Even something this simple has specifications - it has a size.  It can only hold so much.  A beverage company puts something in it.  You take it out.  It's used for storing something.  More commonly, classes can store things and do things.  Think about a modern digital camera as an object.  You take pictures with it - it captures images and stores them.  They also let you do things with the stored images, like cropping and stitching.  Both of these objects, a bottle and a camera, can be represented as classes.

You construct a class by writing what looks a lot like an outline.  There are rules that you must follow to write this outline in the Java language, many of them and they are unambiguous.  In computer programming these rules are called the language's syntax.

Logo had its own syntax.  Its syntax is pretty simple, which is one reason I chose to expose you to it before Java.  Java has a much more complex syntax.  The rest of this lesson will cover the rules for writing a syntactically correct Java class.

Why is this important?  If you follow these rules, the Java compiler will not spit out a bunch of errors.  Life will be good.  Trust me...

A class Consists of...

Here is a breakdown of the source code representation of a Java class.  A class can be broken down into two things:

  1. The first piece is a class-header which consists of the keyword "class" and the name you give to the class.  Names in programming languages are also known as identifiers.
  2. The second piece is the body.  It consists of a pair of open/close squiggly brackets with stuff in between them.

Here is a template for the source code of a class:

   class <identifier>   
   {
      <member>
      ...
   } 
Figure 21.1

When you write a class, you replace <identifier> with the name you want to give your class.  The body of your class is made up of one or more <member>s (the line with "..." on it means any number of the preceding things).  You can use this example every time you write the source code for a class.

Specifically, the keyword "class" should start in the first column of a line followed by the rest of the header information - an identifier in the simplest case. 

The open-squiggly-bracket delimits the header and initiates the class' body.  Some programmers like to place it at the end of the header line; I like to place it on its own line, all by itself.

A close-squiggly-bracket delimits the class' body.  A common practice is to place a close-squiggly-bracket in column 1 by itself.

The contents of the body of a class consists of a collection of <member>s.  Members consist of variables called fields and things it does, called methods (also known as procedures).

The contents of the body (its <member>s) should be indented at least two columns.  Many programmers indent four columns at a time to make the source code easier to read.  The number of columns you indent is not important, but you need to be consistent with whatever amount you choose.  See indentation conventions in the jargon appendix for a longer explanation of why).

There is another convention that you need to be aware of: class identifiers should start with a capital letter and every new word in it should also be capitalized.

Compare the class template above with the Hello World program in the last lesson.  It has a single <member>, a method declaration.  This method (main) is needed in every application.  It is special, so we'll dedicate an upcoming section to it.  But, first I want to cover Java's vocabulary, its keywords.

Java Keywords

Java keywords are words reserved as core building blocks of the Java language.  You may not use them for names of things you create, like class, field and method identifiers.  The Java compiler recognizes these words and treats them special.  Table 21.1 contains all of Java's keywords.  The special meaning of these keywords will be covered as each is introduced in a lesson.

 abstract 
 const 
 finally 
 int 
 public 
 this 
 boolean 
 continue 
 float 
 interface 
 return 
 throw 
 break 
 default 
 for 
 long 
 short 
 throws 
 byte 
 do 
 goto 
 native 
 static 
 transient 
 case 
 double 
 if 
 new 
 strictfp 
 try 
 catch 
 else 
 implements 
 package 
 super 
 void 
 char 
 extends 
 import 
 private 
 switch 
 volatile 
 class 
 final 
 instanceof 
 protected 
 synchronized 
 while 
Table 21.1

The Special Method:
public static void main(String[ ] args)

When we execute a Java application, we use the "java" command which runs the Java Virtual Machine (JVM) and we specify a class file for it to execute.  But, how does the JVM know where to start executing?

ANSWER: It starts with a special method you identify as the "main" method of your application.  This convention is a tradition Java inherited from the "C" programming language.

The source code for main( ) always looks something like:

   public static void main (String[ ] identifier)   
   {
      <statement>
      ...
   } 
Figure 21.2

I'm going to pass on the full explanation behind why we need "public static" in your declaration of "main" but, trust me, those keywords need to be there.  For now, think of the keywords: public and static as special modifiers needed for the method main to be found and accessible.

The identifier can be anything, but it's pretty much a standard that you use the name "args" (which is an abbreviation of arguments) because this is what has been used everywhere.

Summary

Java programs are composed of classes.  Classes are composed of <member>s.  Members are either fields and methods.  Every program needs to have a special method named main.  If you merge the source code I've given you above, you end up with a template for a minimal Java application.  Figure 21.3 shows the template.

   class <identifier>
   {
      public static void main(String[ ] identifier)   
      {
         <statement>
         ...
      }
   } 
Figure 21.3

with the first identifier is the class' name and the second identifier is args.

Memorize this!!!

*NOTE* Remember - it is a defacto standard that all class names start with a capital letter, with additional words in it also capitalized.  As an example, MyClass is proper but myClass and Myclass are not.

*NOTE* Remember - your class identifier must also be the name of the file you enter your source code into.  The file also must have the extension of ".java"

Exercises

  1. Compare the Java program we worked on in the last lesson (class Hello) with the templates in this lesson.  What are the differences?
  2. Write a Java application that displays something (a verse of a song you like, a quote from something you are reading, anything as long as it's a couple of lines long).


Back to A Java Program
Go to the Table of Contents
On to Extending Existing Classes

Public Domain Mark
This work (BFOIT: Introduction to Computer Programming, by Guy M. Haas),
identified by Berkeley Foundation for Opportunities in IT (BFOIT),
is free of known copyright restrictions.