Home Previous Next

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

Overview Assignment(s)[program] #IntList [due 3/4/2017]

Code [recursion] Countdown.java | Power.java | PrintLD.java | Reverse.java | Fibonacci.java | GCD.java {GCDverbose.java}
[interfaces] InterfaceExample.java | InterfaceEG.java | I_ExitStatus.java | TestI_ExitStatus.java | TestSerializable.java | TestClone.java | CSC205_Containers
[moved to next week] MultiArrays.java | TwoDimensionalArrays.java | BYTES.java | ThreeDimensionalArray.java


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
  ...       ...       ....

Another example...

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}


Object Serialization

Any object that implements the Serializable interface can be turned into a sequence of bytes that can be restored fully into the original object.

Benefits.

The Serializable interface is used as a flag -- it has no methods. Some objects may not want to be serialized.

To serialize an object you create some sort of OutputStream object and wrap it inside an ObjectOutputStream object. Then, the object can be serialized by calling writeObject(). Reversing the process is accomplished by creating an InputStream inside a ObjectInputStream and calling the readObject() method.

When an object is serialized, so are all the references it may contain to other objects.

- Object Serialization (java1.1)
   * useful for saving the state of an application/applet
   * objects serialized/deserialized with  ObjectOutputStream  and
     ObjectInputStream, respectively, using the  writeObject()  and
     readObject()  methods
   * primitive types written to stream as if using DataOutputStream;
     otherwise,  writeObject() is called recursively to serialize
     other objects (arrays, strings, objects) -- infinite recursion
     is not a problem (so they say); can end up with an entire
     graph object serialized
   * not all objects can or should be serialized
   * a class is serialable iff it implements Serializable 
      (or Externalizable); no methods defined -- it is a
      marker interface
   * Component implements Serializable; thus, all AWT components
     can be serialized
   * transient  indicates that a field should not be serialized
   * custom serialization is accomplished by overriding  writeObject()
     and  readObject(), and by using  defaultWriteObject()  and
     defaultReadObject() -- note: they must be declared  private
   * classes are assigned a version # -- cannot deserialize a
     class that has a different version # than what was used when
     it was serialized;  'serialver'  program
        + static final long serialVersionUID = 19971209L;
   * serialized applets
      + <applet code=appletName.ser ...>
      + applets can be shipped in a pre-initialized state
   * Externalizable
      + ObjectOutputStream and ObjectInputStream use the
         writeExternal() and readInternal() methods instead
         of writeObject() and readObject(); allows the class
         to take complete control over writing/reading their state

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


Object Cloning

Objects cannot be cloned unless they are created using a class that implements the Cloneable interface.

For a class to use the default implementation of Object.clone(), it must implement the Cloneable interface.

The Cloneable interface is an empty interface -- it is used as a tag only. In many cases, classes that can be cloned override Object.clone().

Object.clone() does a bit-wise copy, which works fine for primitive types, but not necessarily with references. Only individual classes know how to be cloned (if at all). By default, a shallow copy is done versus a deep copy.

If an attempt is made to clone an object that is not cloneable, then the CloneNotSupportedException exception is thrown. This is a checked exception; therefore, it must be caught.

It is common for cloneable classes to override clone() so as to make it public rather than protected.

   The Population class extends class X (which is cloneable), and it
   contains numerous primitive types and a bunch of object references:

      try {
         Population p = (Population)super.clone();
         p.name = new String(getName());
         p.growthRate = (GrowthRate)growthRate.clone();
         p.density = (Density)density.clone();
         return p;
      } catch (CloneNotSupportedException e) { return null; }

From the CoreJava book.

Why clone? You never want to return a mutable object as the value of a method because this violates encapsulation. As a rule of thumb, always use clone whenever you need to return a copy of a mutable data field.

When you start dealing with objects instantiated from classes that you do not know well, then how they clone becomes an unknown.

Here is an example of a program that will result in the throwing of a CloneNotSupportedException.

   class A {
      int a;
      public A (int i) { a = i; }
      public Object clone() throws CloneNotSupportedException {
         return super.clone();
      }
   }
   public class Main {
      public static void main(String[] arg) {
         A a1 = new A(260);
         try {
            A a2 = (A)(a1.clone());
         } catch (CloneNotSupportedException e) {}
      }
   }

      The execeptions occurs because class A calls Object.clone(),
      but it does not implement the  cloneable  interface.

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


Lists

A  list  is a linear data structure whose components can only be accessed sequentially, one after another.

The first item is a list is called the  head  or  front  and the last item is called the  tail ,  back  or  end.

Lists have the following features:

List operations include:

GDT::Java::Code::GoofyIntList.java

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


Home Previous Next