Home Previous Next

CSC205::Lecture Note::Week 02
Assignments | Code | Handouts | Resources | Email Thurman | Tweets::@compufoo
GDT::Bits:: Time  |  Weather  |  Populations  |  Special Dates

Overview Assignment(s)[program] #RecursionPlay [due 2/6/2017]

Code Import.java [last week] | HelloWorldOO.java | PolyNumber.java | XYZ.java | Arrays.java | Exceptions.java | TestExceptions.java | Rot13.java


CSC205 Competency 1: Modern Software Engineering Techniques

Wikipedia.org::Software development methodology

{TopOfPage} {Oracle.com::API Specification | Tutorial} {Derek Banas Videos}


CSC205 Competency 2: Object-Oriented Programming Techniques

Introduction to Classes

A class is a blueprint or template that describes an object.

Class Syntax
   classDeclaration {
      classBody
   }
Syntax of a class declaration:
   [ modifiers ] class ClassName [ extends SuperClassName ]
                                 [ implements InterfaceNames ]

   Some example modifiers are:  public, abstract, final 
   If no modifier is specified, then it defaults to "package."

The class body contains static data members, instance data members, static methods and instance methods.

By convention, class names begin with an uppercase letter.

About Constructor Methods

A constructor is a special method that is used to help guarantee that objects are initialized to a "valid" or "sane" state when they are created (instantiated).

{TopOfPage} {Oracle.com::API Specification | Tutorial} {Derek Banas Videos}


Review: The Anatomy of a Class

Let's assume we have the following class definition.

   public class ClassAnatomy {
      static int key;
      int color;

      public static void main(String[] a) {
         int i;
      }
      public void foo() { }
   }

The names key and color are member variables. In other words, they are members of the class and are defined outside of any method.

The member variable key is a class variable and color is an instance variable. All static defined variables are class variables.

All member variables are initialized to zero (all-bits-zero) by the JVM.

The variable named i is a local variable and it is local to the method named main(). The variable i can only be used inside the main() method. Local variables are not initialized to any known value and in many cases that Java compiler will not let an un-initialized local variable be used.

The variable named a is a local variable to the method named main(). It is also called a parameter. Parameters are initialized to the value passed as an argument when the method is called.

Method main() is a class method and method foo() is an instance method. Instance methods can only be used with a specific instance of the class.

Aggregate Classes

Aggregate classes are used to implement has-a relationships.

Example.

   class Game {
      Controller c;
      ...
   }

   class Controller {
      ...
   }

A Game object has-a Controller object.

Inheritance

Inheritance allows classes to be defined in terms of other classes.

In Java, inheritance is implemented when a class extends another class.

Polymorphism is when an object of a child class is used as an object of its parent class. In other words, an object of a given class can have multiple forms, either as it own class or as any class it extends.

By default, all classes extend the Object class that comes with the JSDK. Therefore, every object is-an object of class Object.

Some benefits obtained from using inheritance are.

You are not limited to just one layer of inheritance. The inheritance tree, or class hierarchy, can be as deep as needed.

In general, the further down in the hierarchy a class appears, the more specialized its behavior. [Class extension is most commonly used for specialization.]

The following is an example class hierarchy.

                        BankAccount
                     (account#, balance)
                              |
                    +---------+----------+
                    |                    |
            CheckingAccount       SavingsAccount
                                         |
                                +--------+------------+
                                |                     |
                          PassBookAccount     InvestmentAccount
                                       
   public class BankAccount extends Object {...}
   public class CheckingAccount extends BankAccount {...}
   public class SavingsAccount extends BankAccount {...}
   public class PassBookAccount extends SavingsAccount {...}
   public class InvestmentAccount extends SavingsAccount {...}

   CheckingAccount  "is-a"  BankingAccount  and  PassBookAccount
   "is-a"  SavingsAccount  and so on.

	Note:  BankAccount extends Object.

Java supports single-inheritance only (i.e. a class can extend only one class).

Typical characteristics of a derived class are.

The representation of the parent class cannot be altered (i.e. neither data nor functionality [behavior] can be removed).

Functionality defined in the parent class can be modified by overriding the appropriate methods in the derived class.

If a parent method is overridden in the child class and the child wants to invoke the parent's method, then the super keyword must be used to qualify the method name.

   class Foo {
      void echo() {...}
   }

   class Bar extends Foo {
      void echo() { 
         super.echo();  //invoke echo() implemented in the parent class
         ...
      }
   }

From 1999 (so it might be dated/stale): JavaWorld.com::How to avoid traps and correctly override methods from java.lang.Object

{TopOfPage} {Oracle.com::API Specification | Tutorial} {Derek Banas Videos}


Interfaces

From the The Java Programming Language by Arnold, Gosling, Holmes.

The fundamental unit of programming in Java is the class, but the fundamental unit of object-oriented design is the type. Interfaces define types in an abstract form as a collection of methods or other types that form the contract for that type.

An interface is defined using the keyword interface rather than class.

An interface contains no instance variables, nor does it contain any method implementations. You cannot create instances of an interface.

   interface Foo { ... }

   //! Foo f = new Foo();   // not legal

An interface can declare three kinds of members:

All interface members are implicitly public.

A class guarantees to implement the methods of an interface by using the implements keyword when the class is defined.

   class X implements Y

Any class that implements an interface must define (i.e. implement) the methods, if any, declared in the interface.

A class can implement more that one interface. In addition, a class can extend another class and still implement one or more interfaces.

   class X implements Y, Z { ... }
   class X extends A implements Y, Z { ... }

To an extent, interfaces support the concept of multiple inheritance.

Common interfaces from the java.lang package:

An interface can be used to "tie" together classes that are in separate inheritance trees.

                  Object
                    |
                Assignment               Interface:  Submitable
                    |
            Exam   Program   Homework
            ...    ...       ...



             Object
               |
              Game                       Interface:  Submitable
               |
  Guessing  Yahtzee   Blackjack
  ...       ...       ....

An interface can be used to encapsulate a collected of related manifest constants (i.e. simulate an enum in C).

   interface ExitStatus {
      int EXIT_SUCCESS = 0;
      int EXIT_FAILURE = 1;
   }

When an interface declares named constants, then they are implicitly defined to be public, static, and final. [blank finals are not allowed]

Methods declared in an interface are implicitly abstract.

An interface can extend (i.e. inherit) other interfaces.

   interface Sortable { ... }
   interface Searchable { ... }
   interface Container extends Sortable, Searchable { ... }
Any class that implements interface Container must also implement the Sortable and Searchable interfaces.

Although you cannot instantiate an object using an interface, you can use an interface as the type for variable and assign to that variable any object whose class implements the interface. This allows for polymorphic run-time binding.

   interface Container { ... }

   class List implements Container { ... }

   List list = new List();
   ...
   Container c = list;  // list is a container

From a naming convention perspective, many interfaces have a -able suffix applied to them.

{TopOfPage} {Oracle.com::API Specification | Tutorial} {Derek Banas Videos}


Abstract Classes and Methods

An abstract class is one that is used for derivation only. Objects cannot be instantiated from an abstract class. Attempting to do so at compile-time is a syntax error. Attempting to do so at run-time causes an error.

An abstract class can contain data and methods. Some of the methods may in turn be declared to be abstract. Abstract methods have no implementations.

If a class contains an abstract method, then it must be an abstract class. However, you can have an abstract class that doesn't have any abstract methods.

An abstract method is a method that is declared, but the method's implementation is found in one of the derived classes. In otherwords, the classes that extend an abstract class are responsible for providing implementations of the abstract methods.

   Syntax:

      abstract class SomeClassName { ... }

The Number class in the java.lang package represents the abstract concept of numbers. It is used as a superclass to the wrapper classes (e.g. Integer and Float).

   public abstract class Number implements java.io.Serializable {
       public abstract int intValue();
       public abstract long longValue();
       public abstract float floatValue();
       public abstract double doubleValue();
       public byte byteValue() { return (byte)intValue(); }
       public short shortValue() { return (short)intValue(); }
   }

Each wrapper class (e.g. Byte, Integer, etc.) extends Number (except for Character).

The Number class ensures that there is common functionality across all classes that extend it (e.g. intValue()).

Every class that inherits from Number must implement the methods that are defined to be abstract. The Number class contains a couple of non-abstract methods (shortValue() and byteValue()); in other words, these methods are implemented in the class. If you were to write a class that extends Number, then you would have to check to see if the non-abstracts methods work for you specific type of number. If they don't, then you can provide implementations for the non-abstract methods by overriding them.

You cannot instantiate a Number object. You can, however, have a handle (i.e. object variable) to a Number object (e.g. Number num). The values that can be assigned to a Number object variable are handles to objects instantiated from classes that extend the Number class.

   Number num = new Integer(100);  // a typecast is not necessary

Docs.Oracle.com::Tutorial::Abstract Methods and Classes

{TopOfPage} {Oracle.com::API Specification | Tutorial} {Derek Banas Videos}


Arrays

An array is a aggregate (collection, set, group, list) of individual data values with two characteristics: it is ordered and homogeneous.

The following are some array-related terms:

An array is homogeneous because each element must be of the same type. Example: an array of int values, an array of float values, an array of char values, and array of Object values (handles, references, pointers).

An array is ordered because it has a 1st element, a 2nd element, a 3rd element, and so on. Array elements are probably stored in contiguous memory locations [this is definitely true in C and C++; in Java it is left up to the JVM implementors].

Here is a list of items you should understand when using arrays:

Defining an Array of Primitive Types

The following creates an array of long values:

   long[] ssNbrs;      // an array of social security numbers

      // ssNbrs is an object variable that is going to point to
      // an array of  long  values; at this point and time, it 
      // doesn't point to anything (i.e. it is equal to  null)

   ...

   int n = fooA();    // get the array length somehow

   ...

   ssNbrs = new long[n];

      // array length is decided at run-time (i.e. we don't know
      // the array length at compile-time; the information is
      // obtained from a user, or from a database file, etc.)
      // two things occur when an array is defined:  memory is
      // allocated from the heap and the memory is initialized
      // to the appropriate default values  [0 for integral and
      // floating-point types,  false  for  boolean  arrays, and
      // null  for arrays of object references]

   ...

   for (int i = 0; i < ssNbrs.length; i++)
      ssNbrs[i] = -1L;  // initialize each element to -1

      // use the  <  relational operator is important; a common
      // programming defect is to use the  <=  operator -- what
      // would happen if we did?

   ...

   ssNbrs = new long[2 * n];

      // after an array has been created, its length if fixed; if you
      // need more elements, then you need to create a new array;
      // now  ssNbrs  references (i.e. points to) an entirely
      // different array of long values; the original array still
      // exists, but the reference to it has been lost and it are
      // not able to copy the original values into the new array

   long[] orig = ssNbrs;
   ssNbrs = new long[n * 3];

   for (int i = 0; i < orig.length; i++) ssNbrs[i] = orig[i];

      // the handle to the original array is stored in the array variable
      // named  orig.  The new array is allocated and the contents of
      // the original arrray is copied to the new array

   System.arraycopy(orig, 0, ssNbrs, 0, orig.length);

      // arraycopy(Object src, int srcOffset, 
      //           Object destdst, int destOffset, int count);
      //
      // the  arraycopy()  method copies a region of one array, src,
      // beginning at element  srcOffset, to another array, dst,
      // beginning at element  destOffset;  count  elements are copied.
      // note:  the arrays must already be allocated

   Tip:  In the control-EXPR of the loop, I'm better off using
         ssNbrs.length  rather than the variable  'n'  because 
         since 'n' is a variable, it could be modified such that 
         the EXPR  n == ssNbrs.length  is not true.
Defining an Array of Objects

The following code snippet an array of object variables.

   Integer[] iArray;

      // iArray  is a reference (handle, pointer) to an array of 
      // Integer references -- at this point and time, it doesn't
      // "point" to any array

   ...

   iArray = new Integer[10];

      // array length is known compile-time; an array to store 
      // 10 Integer references is created; each array element is 
      // initialized to   null   (recall,  null  is a Java keyword)

   ...

   for (int i = 0; i < iArray.length; i++)
      iArray[i] = new Integer(i);

         // an  Integer  object is created and a reference to it is
         // stored in  iArray; when the Integer object is created,
         // it is initialized to the value of 'i'...

Arrays are always stored on the heap. The reference to the array will be stored either on the stack or in the data segment depending on where it is defined.

The following are some comments on the efficiency of arrays:

Arrays.java | A.java

{TopOfPage} {Oracle.com::API Specification | Tutorial} {Derek Banas Videos}


Exceptions

Exceptions are "exceptional" conditions that can occur while a program is executing (i.e. running). Some exceptions are caused due to software defects (e.g. using a null object handle, or indexing beyond the bounds of an array).

   String s = null;
   String s1 = "hello";
   ...
   if (s.equals(s1)) { ... }     //this will cause an exception
   ...
   int[] array = new int[10];
   ...
   array[array.length] = 200;    //this will cause an exception

Exceptions are also generated by errors that are beyond the control of the program (e.g. the program needs to access a file that doesn't exist, or the program needs to fetch a webpage given an invalid [mal-formed] URL).

Exceptions can be "caught" by programs, but if an exception does occur that isn't caught, then the program (assuming it is non-graphical) terminates. (A GUI program returns to the user interface).

Exceptions are objects that are created from the Exception and RuntimeException classes.

          Throwable
             |
   Error               Exception
   .....               /  ...  \
                  IOException   RuntimeException 
                    (checked)     (unchecked)

There are two categories of exceptions: checked and unchecked. Checked exceptions must be caught (otherwise, your program will not compile). Unchecked exceptions typically are not caught (i.e. they cause your program to terminate when they occur).

A method can throw an exception when it encounters a situation it cannot handle. There are numerous methods that come with the JCL (java class library) that throw exceptions.

A method declaration must contain a list of the the checked exceptions it may throw.

   public int someMethod() throws IOException, MalformedURLException

A method does not need to declare RuntimeException inherited exceptions that it may throw.

If a method overrides a method from a parent class, then the child method cannot throw more checked exceptions that the parent method does.

A method can say it throws exceptions that it really doesn't throw.

Catching an Exception

Whenever a method is called that throws a checked exception, then that method call must be called from within a try block and an exception handler (catch block) must be implemented.

   try {
      ...
      someMethodThatThrowsIOException();
      ...
   } catch (IOException e) {
      ...
   }

If an exception occurs, then the flow control of the program jumps to a catch block. All remaining statements, if any, within the try block are skipped. If no exception is thrown, then the catch blocks are skipped.

A try block must be a compound statement. Ditto for the catchblocks.

The catch blocks are passed an argument: a reference to the exception (which may or may not be used).

Throwing an Exception

An exception is thrown as follows.

   throw new EOFException();

         or

   throw new EOFException("file's empty");
      //supply additional information about the exception
      //this information can help the client "fix" the problem

A method that throws an exception does not return to the caller.

An exception can be re-thrown. You may want to do this in the event an exception occurs: you catch it locally to clean up any locally allocated objects and/or system resources, and then "pass" the exception on to those who know about handling it.

Exception A can be caught, and exception B can be thrown.

Creating an Exception Class

You can create your own exceptions by extending Exception or some child class of Exception.

   class MyException extends Exception {
      public MyException() {}
      public MyException(String msg) { super(msg); }
   }
Terminology

The following exception terminology was obtained from Just Java by Peter van der Linden:

Note Java Other Languages
An error condition that happens at run time Exception Exception
Causing an exception to occur Throwing Raising
Capturing an exception that has just occurred, and executing statements to resolve it in some way Catching Handling
The block that does this Catch clause Handler
The sequence of call statements that brought control to the method where the exception happened Stack trace Call chain
Miscellaneous Comments

Detect errors at a low level, handle them at a high level.

Use exceptions only for exceptional situations.

{TopOfPage} {Oracle.com::API Specification | Tutorial} {Derek Banas Videos}


Home Previous Next