Personal tools
You are here: Home Classes Fall 2004 - Spring 2005 Old CS 160 CS 160 Lecture 2
Navigation
Log in


Forgot your password?
« May 2008 »
Su Mo Tu We Th Fr Sa
123
456789 10
11121314151617
18192021222324
25262728293031
 
Document Actions

CS 160 Lecture 2

by admin last modified 2005-05-25 15:41

Java Programming

Classes and Objects

What is an object?

An object is an abstract entity used to model some entity in a problem domain.

What is a class?

A class is a category of similar objects.  What characterizes a class is the set of properties that the objects have in common.  The common properties are the data fields and methods defined in the definition of the class.  An object is an instance of a class.  A class is to a cookie cutter as an object is to a cookie.

example  An automobile class

Data fields:
  • VIN
  • year
  • make
  • model
  • body type
Methods:
  • goForward
  • goBackward
  • getSpeed
  • getOdometerReading

A Java programmer writes class definitions, which describe in detail the behavior of the objects in the class.  In Java, every line of code is a part of a class definition.

A class definition encapsulates a set of data fields and the methods used to operate on them.  This principle is at the heart of object-oriented programming.  It has several important ramifications, including
  • avoiding uncontrolled access to data values, making it easier to find bugs involving the value
  • making the class a self-contained unit that can be used by other classes
A method is a procedure carried out by an object in response to a message from another object, or from itself.  The data held by an object is its memory, or its state, which it retains between method calls.  


example  A class which keeps track of the number of times it has been called.  It has one method, timesCalled().

class SimpleCounter {

    private int callCount;

    public int timesCalled()
    {
        callCount++;
        return callCount;
    }
}



In some cases, a class may not have any data.

example  A class used to determine whether or not numbers are prime

public class PrimeTester {

    public boolean isPrime(int n)
    {
        boolean prime = true;
        int divisor = 2;        //  test divisor
       
        while( prime && divisor * divisor <= n ){
            if ( n % divisor == 0 )
                prime = false;
            divisor ++;
        }
       
        return prime;
    }
}


Using a class


To use a class, one must

1.    Declare a variable whose data type is the class.
2.    Create an instance of the class; that is, an object.  This is called instantiation, performed by the new operator.
3.    Save a reference to the object in the variable.
4.    Call the object's methods, using the form

        variable-name.method-name(arguments);

        (The parentheses are needed even if there are no arguments.)

example
 A program segment which prints the first 100 prime numbers, using the Prime Tester class.

    PrimeTester primeTester = new PrimeTester();
    int count = 0;
    int try = 2;
    while ( count < 100 ){
        if(primeTester.isPrime(try)){
            count++;
            System.out.println("The " + count + "th prime is " + try);
            }
        ++try;
    }


Okay, so if all the code is in methods within classes, and objects get created by other classes using the new operator, how does a program get started?  That is, how does the first object get created?

Actually, it is possible for an entire Java program to run without ever instantiating any objects!  This is because a class can have what are called static or class methods.  They are shared by all class members, and don't require that any object of the class to exist in order to call them.  (A class can have static data fields, too.) Normal methods and variables are specific to an object; they are called instance methods and instance variables.


example  A Java program that doesn't instantiate any objects

import java.io.*;

class NoObject {
    static public void main () {
        System.out.println("Hello, world");
    }
}

example  An equivalent program using an object

class HelloWorld {

    public void writeIt(){
        System.out.println("Hello, world");
    }

    static public void main(String[] args)
    {
        HelloWorld helloWorld = new HelloWorld();
        helloWorld.writeIt();
    }
}

So the job of the programmer is to:

1.    Identify the objects which will have a role in the solution of the problem, and the interactions between them.

2.    Identify where off-the-shelf objects can be used.  For objects which must be written from scratch, follow steps 3-6.

3.    Define the interface to each class of object; that is, the services provided, the public methods.

4.    For each class, determine what state information will be needed to implement the methods.

5.    For each method, design an algorithm to implement it.

6.    Write code for each method's algorithm.  (Notice that we don't do away with procedural programming.  We still have to write code for methods.)

Decomposing a problem into objects and specifying their interactions is not an easy problem.  Software engineers use design patterns to help with this task.  A design pattern is a group of classes and relationships between classes which has been found to be useful in solving a variety of problems.  The goal is to be able to reuse other programmers' ideas at a higher level (i.e., the design level), in contrast to objects, which allow use to reuse code.

Compiling and running Java programs

Java source code is written in a file with the .java extension.  Normally, each .java file contains the definition of a single public class.  The name of the class must be the same as the name of the file; for example a class called MyClass would be defined in the file MyClass.java.

In order to be executed on the Java Virtual Machine (JVM), the Java code must be translated into bytecodes; that is, the machine language of the JVM.  This translation is performed by the Java compiler javac, which is part of the Java Development Kit, as follows:

    javac MyClass.java

The result of the compilation is called a class file.  The name of the class file uses the name of the class, with an extension of .class; in this case, the name of the class file is MyClass.class.

If the class has a public static void method called main, it can be executed directly by the Java interpreter, using the command

    java MyClass

The interpreter loads the bytecodes from the class file and runs them on the JVM.

Arguments may be passed to the main method on the command line.  (The standard signature for the main method is public static void main (String args[]).)   For example, the command

    java MyClass cat dog gerbil canary

would call the main method in MyClass with args = { "cat", "dog", "gerbil", "canary" } as its argument.





 

Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: