Introduction to Object-Oriented Programming, Sample Programs, Set 1

Published:  November 29, 2001
Revised:  June 1, 2005
By Richard G. Baldwin

Java Programming Tutorial # 9000


Preface

This is the first in a miniseries of lessons designed specifically to help the students in my "Introduction to Object-Oriented Programming" course study for their exams.  However, others may find the lesson useful as well.

The lesson consists of a set of simple programs, each designed to illustrate one or more important Java OOP concepts.  The concepts involved are identified in the comments at the beginning of each program.

The programs are designed to illustrate the code without providing a detailed discussion of the code.  You are referred to the other lessons in my online Java tutorials for detailed discussions of the OOP concepts illustrated by these programs.

Sample Programs

Program Samp002.java
 
/*File Samp002 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
  Write Java application
  The main method
  Display String literal on console
  
The output consists of the following
line of text on the screen:
  
Hello World

**************************************/

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

Program Samp004.java
 
/*File Samp004 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
  Instantiate object of existing class
  Invoke method on object
  
The output consists two lines of text
similar to the following.  The first
line will show the current date and
time.  The second line will show the
number of milliseconds since Jan 1,
1970.

Wed Nov 28 13:50:50 CST 2001
1006977050803

**************************************/

import java.util.*;
class Samp004{
  public static void main(
                        String[] args){
    //Instantiate object of Date class
    Date refVar = new Date();
    System.out.println(refVar);
    long primVar = refVar.getTime();
    System.out.println(primVar);
  }//end main 
}//end class Samp004

Program Samp006.java
 
/*File Samp006 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
  Instantiate anonymous Date object
  Invoke method on anonymous Date 
    object to get long value
  Pass long value to constructor 
    for Random class
  Invoke method on object of
    Random class to get random 
    int value
  Display random int value
  
The output consists of a single random
value similar to the following:
  
472076870

**************************************/

import java.util.*;
class Samp006{
  public static void main(
                        String[] args){
    Random refVar2 = 
      new Random(new Date().getTime());
    System.out.println(
                    refVar2.nextInt());
  }//end main
}//end class Samp006

Program Samp008.java
 
/*File Samp008 
Copyright 2001, R.G.Baldwin
Rev 06/01/05

Tested using JDK 1.3 under Win

Illustrates:
  Instantiate anonymous Date object
  Invoke method on anonymous Date 
    object to get long value
  Pass long value to constructor 
    for Random class
  Invoke method on object of
    Random class to get random 
    int value
  Use cast operator to convert random
    int value to type byte
  Display random byte value
  
The output consists of a single random
value similar to the following:
  
110

**************************************/

import java.util.*;
class Samp008{
  public static void main(
                        String[] args){
    Random refVar2 = 
      new Random(new Date().getTime());
    System.out.println(
              (byte)refVar2.nextInt());
  }//end main
}//end class Samp008

Program Samp010.java
 
/*File Samp010 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
  Array objects
  Conversion from int to double 
    during division of int value
    by double value
  
The output consists of the following 
four lines of text on the screen.  
Note that three of the values are
integer values while one is a floating
value.  

0 
1 
2.0 
3

**************************************/

class Samp010{
  public static void main(
                        String[] args){
    int[] arrayRef = new int[4];
    for(int cnt=0;cnt<arrayRef.length;
                                cnt++){
      arrayRef[cnt] = cnt;
    }//end for loop
    
    for(int cnt=0;cnt<arrayRef.length;
                                cnt++){
      if(cnt == 2)
        System.out.println(
              arrayRef[cnt]/1.0 + " ");
      else
        System.out.println(
              arrayRef[cnt] + " ");
    }//end for loop
  }//end main
}//end class Samp010

Program Samp012.java
 
/*File Samp012 
Copyright 2001, R.G.Baldwin
Rev 06/01/05

Tested using JDK 1.3 under Win

Illustrates:
  Reference variables
  Defining new classes
  Instantiating objects of new
    classes
  Overriding toString method in one
    new class, but not the other
  Invoking toString method on objects
    of both new classes and displaying
    the results
  
The output consists of the following
two lines of text:
   
Richard Baldwin
Samp012ClassB@273d3c

**************************************/

import java.util.*;
class Samp012{
  public static void main(
                        String[] args){
    Samp012ClassA refVar1 = 
                   new Samp012ClassA();
    String stringVar = 
                    refVar1.toString();
    System.out.println(stringVar);
    
    Samp012ClassB refVar2 = 
                   new Samp012ClassB();
    stringVar = refVar2.toString();
    System.out.println(stringVar);
  }//end main
}//end class Samp012
//===================================//
  
class Samp012ClassA{
  //overridden toString method
  public String toString(){
    return "Richard Baldwin";
  }//end overridden toString()
}//end class Samp012ClassA
//===================================//
class Samp012ClassB{
  //no overridden toString method
}//end class Samp012ClassB

Program Samp014.java
 
/*File Samp014 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
  Defining a noarg constructor
  
The output consists of the following
line of text:
   
Richard Baldwin

**************************************/

import java.util.*;
class Samp014{
  public static void main(
                        String[] args){
    new Samp014MyClass();
  }//end main
}//end class Samp014
//===================================//
  
class Samp014MyClass{

  Samp014MyClass(){//constructor
    System.out.println(
                    "Richard Baldwin");
  }//end constructor
  
}//end class Samp014MyClass

Program Samp016.java
 
/*File Samp016 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
  Defining a parameterized constructor
  
The output consists of the following
line of text:
   
Richard Baldwin

**************************************/

import java.util.*;
class Samp016{
  public static void main(
                        String[] args){
    new Samp016MyClass(
                    "Richard Baldwin");
  }//end main
}//end class Samp016
//===================================//
  
class Samp016MyClass{

  //parameterized constructor
  Samp016MyClass(String dataIn){
    System.out.println(dataIn);
  }//end constructor
  
}//end class Samp016MyClass

Program Samp018.java
 
/*File Samp018 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
  Class variables
  Accessing class variable using
    class name
  Accessing class variable using
    reference to object
  Only one copy of class variable 
    exists regardless of number of
    objects instantiated from the 
    class (including none)
  
The output consists of the following
six lines of text:

6
6
6
12
12
12 

**************************************/

import java.util.*;
class Samp018{
  public static void main(
                        String[] args){
    Samp018MyClass.classVar = 6;
    System.out.println(
              Samp018MyClass.classVar);
    
    Samp018MyClass refVar1 = 
                  new Samp018MyClass();
    System.out.println(
                     refVar1.classVar);
    
    Samp018MyClass refVar2 = 
                  new Samp018MyClass();
    System.out.println(
                     refVar2.classVar);
    
    refVar2.classVar = 12;
    System.out.println(
              Samp018MyClass.classVar);
    System.out.println(
                     refVar1.classVar);
    System.out.println(
                     refVar2.classVar);
  }//end main
}//end class Samp018
//===================================//
  
class Samp018MyClass{
  static int classVar;
}//end class Samp018MyClass

Program Samp020.java
 
/*File Samp020 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
  Instance variables
  Cannot access instance variable using
    class name
  Accessing instance variable using
    reference to object
  Every object has its own copy of each
    instance variable
  
The output consists of the following
six lines of text:

6
12
10
20 

**************************************/

import java.util.*;
class Samp020{
  public static void main(
                        String[] args){
    //Following statements produce
    // compiler errors
//  Samp020MyClass.instanceVar = 6;
//  System.out.println(
//         Samp020MyClass.instanceVar);
    
    Samp020MyClass refVar1 = 
                  new Samp020MyClass();
    refVar1.instanceVar = 6;
    System.out.println(
                  refVar1.instanceVar);
    
    Samp020MyClass refVar2 = 
                  new Samp020MyClass();
    refVar2.instanceVar = 12;
    System.out.println(
                  refVar2.instanceVar);
    
    refVar1.instanceVar = 10;
    refVar2.instanceVar = 20;
    System.out.println(
                  refVar1.instanceVar);
    System.out.println(
                  refVar2.instanceVar);
  }//end main
}//end class Samp020
//===================================//
  
class Samp020MyClass{
  int instanceVar;
}//end class Samp020MyClass

Program Samp022.java
 
/*File Samp022 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
  Overloaded class methods

The output consists of the following 
four lines of text on the screen.  

6
2.727272727272727
6
2.727272727272727

**************************************/

import java.util.*;
class Samp022{
  public static void main(
                        String[] args){
    int intVar = 6;
    double doubleVar = 6/2.2;
    System.out.println(intVar);
    System.out.println(doubleVar);
    
    Samp022MyClass.store(intVar);
    System.out.println(
        Samp022MyClass.fetchIntData());

    Samp022MyClass.store(doubleVar);
    System.out.println(
      Samp022MyClass.fetchDoubData());
   
  }//end main
}//end class Samp022
//===================================//
  
class Samp022MyClass{
  private static int classIntVar;
  private static double classDoubleVar;

  //overloaded class method
  static void store(int dataIn){
    classIntVar = dataIn;
  }//end store
  
  //overloaded class method
  static void store(double dataIn){
    classDoubleVar = dataIn;
  }//end store
  

  //class method
  static int fetchIntData(){
    return classIntVar;
  }//end fetchIntData
  
  //class method
  static double fetchDoubData(){
    return classDoubleVar;
  }//end fetchDoubData
}//end class Samp022MyClass

Program Samp024.java
 
/*File Samp024 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
  Overloaded instance methods
  
The output consists of the following
two lines of text:
  
3
8 

**************************************/

import java.util.*;
class Samp024{
  public static void main(
                        String[] args){
    Samp024MyClass refVar1 = 
                  new Samp024MyClass();
    
    refVar1.setData(3);
    System.out.println(
                    refVar1.getData());
    refVar1.setData(new Integer(8));
    System.out.println(
                    refVar1.getData());
    
  }//end main
}//end class Samp024
//===================================//
  
class Samp024MyClass{
  private int instanceVar;
  
  //overloaded instance method
  void setData(int dataIn){
    instanceVar = dataIn;
  }//end setData()
    
  //overloaded instance method
  void setData(Integer dataIn){
    instanceVar = dataIn.intValue();
  }//end setData()
        
  int getData(){
    return instanceVar;
  }//end getData()
}//end class Samp024MyClass

Program Samp030.java
 
/*File Samp030 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
  Reference variables
  Class variables 
  Instance variables
  Noarg constructor
  Class methods
  Instance methods
  Overridden toString method
  Overloaded class methods
  Overloaded instance methods
  Instantiating objects
  Display on console
  Invoking methods on anonymous objects
  Array objects
  Casting
  Conversion from int to double 
    during division
  Invoking class methods using class
    name
  Invoking instance methods using
    reference to object
  
The output consists of the following 
five lines of text on the screen.  
Because the program uses random 
data, the actual values will differ 
from one run to the next. 

Samp030
Richard
Baldwin
-78 -81.0 -51 -61 
-78 -81.0 -51 -61

**************************************/

import java.util.*;
class Samp030{
  public static void main(
                        String[] args){
    Samp030MyClass refVar1 = 
                  new Samp030MyClass();
    System.out.println(refVar1);
    
    Random refVar2 = 
      new Random(new Date().getTime());
    int[] arrayRef = new int[4];
    for(int cnt=0;cnt<arrayRef.length;
                                cnt++){
      arrayRef[cnt] = 
               (byte)refVar2.nextInt();
      if(cnt==1)
      System.out.print(
              arrayRef[cnt]/1.0 + " ");
      else
      System.out.print(
                  arrayRef[cnt] + " ");
    }//end for loop
    System.out.println();
    
    Samp030MyClass.store(arrayRef[0]);
    System.out.print(
          Samp030MyClass.fetchIntData()
                                + " ");
    Samp030MyClass.store(
                      arrayRef[1]/1.0);
    System.out.print(
       Samp030MyClass.fetchDoubleData()
                                + " ");
    refVar1.setData(arrayRef[2]);
    System.out.print(
              refVar1.getData() + " ");
    refVar1.setData(
             new Integer(arrayRef[3]));
    System.out.println(
                    refVar1.getData());
    
  }//end main
}//end class Samp030
//===================================//
  
class Samp030MyClass{
  private static int classIntVar;
  private static double classDoubleVar;
  private int instanceVar;
  
  Samp030MyClass(){//constructor
    System.out.println("Samp030");
    System.out.println("Richard");
  }//end constructor
  
  public String toString(){
    return "Baldwin";
  }//end overridden toString()

  //overloaded method
  static void store(int dataIn){
    classIntVar = dataIn;
  }//end store
  
  //overloaded method
  static void store(double dataIn){
    classDoubleVar = dataIn;
  }//end store
  
  static int fetchIntData(){
    return classIntVar;
  }//end fetchIntData
  
  static double fetchDoubleData(){
    return classDoubleVar;
  }//end fetchDoubleData
  
  //overloaded method
  void setData(int dataIn){
    instanceVar = dataIn;
  }//end setData()
    
  //overloaded method
  void setData(Integer dataIn){
    instanceVar = dataIn.intValue();
  }//end setData()
        
  int getData(){
    return instanceVar;
  }//end getData()
}//end class Samp030MyClass

Program Samp032.java
 
/*File Samp032 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
  Use of absolute value method of Math
    class
  Use of modulus operator to 
    distinguish between even and odd 
    values

The output consists of four lines of
text similar to the following.  Note
however that random values are used
so the odd/even sequence may change
from one run to the next.

1728897982
Value is even
1728897983
Value is odd

**************************************/

import java.util.*;
class Samp032{
  public static void main(
                        String[] args){
    Random refToRNGen = 
      new Random(new Date().getTime());
    int var = refToRNGen.nextInt();
    System.out.println(Math.abs(var));
    if(Math.abs(var)%2 == 0){
      System.out.println(
                      "Value is even");
    }else{
      System.out.println(
                       "Value is odd");
    }//end else

    var++;//increment the value

    System.out.println(Math.abs(var));
    if(Math.abs(var)%2 == 0){
      System.out.println(
                      "Value is even");
    }else{
      System.out.println(
                       "Value is odd");
    }//end else
  }//end main
}//end class Samp032

Program Samp034.java
 
/*File Samp034 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
 Behavior of default equals method
 The this keyword

The output consists of the following
two lines of text:
   
true 
false 

**************************************/

import java.util.*;
class Samp034{
  public static void main(
                        String[] args){
    Samp034Class refVarA = 
                   new Samp034Class(5);
    Samp034Class refVarB = 
                   new Samp034Class(5);

    //Test object equal to itself.
    System.out.println(
              refVarA.equals(refVarA));

    //Test object equal to another
    // object of same class containing
    // same data values
    System.out.println(
              refVarA.equals(refVarB));
      
  }//end main
}//end class Samp034  
//===================================//
  
class Samp034Class{
  private int data;
  
  Samp034Class(int data){//constructor
    this.data = data;
  }//end constructor
  
}//end class Samp034Class

Program Samp036.java
 
/*File Samp036 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
 Simple overridden equals method for
   String data

The output consists of the following
three lines of text:

true
true 
false 

**************************************/

import java.util.*;
class Samp036{
  public static void main(
                        String[] args){
    Samp036Class refVarA = 
               new Samp036Class("Joe");
    Samp036Class refVarB = 
               new Samp036Class("Joe");
    Samp036Class refVarC = 
               new Samp036Class("Tom");

    System.out.println(
        refVarA.equals(refVarA) + " ");
    System.out.println(
              refVarA.equals(refVarB));
    System.out.println(
              refVarA.equals(refVarC));
  }//end main
}//end class Samp036  
//===================================//
  
class Samp036Class{
  private String data;
  
  //constructor
  Samp036Class(String data){
    this.data = data;
  }//end constructor
  
  public boolean equals(
                Samp036Class objRefIn){
    return this.data.equals(
                        objRefIn.data);
  }//end overridden equals()
  
}//end class Samp036Class

Program Samp038.java
 
/*File Samp038 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
 Counting number of objects 
   instantiated from same class
 String concatenation

The output consists of the following
three lines of text:
  
1 Joe
2 Sue
3 Tom

Note, this is one of the small number
of valid uses for non-final class
variables. 

**************************************/

import java.util.*;
class Samp038{
  public static void main(
                        String[] args){
    Samp038Class refVarA = 
               new Samp038Class("Joe");
    Samp038Class refVarB = 
               new Samp038Class("Sue");
    Samp038Class refVarC = 
               new Samp038Class("Tom");
  }//end main
}//end class Samp038  
//===================================//
  
class Samp038Class{
  private String data;
  private static int count = 0;
  
  //constructor
  Samp038Class(String data){
    this.data = data;
    System.out.println(
                 ++count + " " + data);
  }//end constructor
  
}//end class Samp038Class

Program Samp040.java
 
/*File Samp040 
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
 Overridden equals() method
 Class variable for counting object 
   instantiations

The output consists of the following 
three lines of text.  The order of
the words false and true is determined 
by the value of a random number, and 
may be different each time the program
is run.

Samp040
Richard Baldwin
false true 

**************************************/

import java.util.*;
class Samp040{
  public static void main(
                        String[] args){
    Samp040Class refVarA = 
                    new Samp040Class();
    Samp040Class refVarB = 
                    new Samp040Class();
    
    Random refToRNGen = 
      new Random(new Date().getTime());

    int var3 = refToRNGen.nextInt();
    int var4 = refToRNGen.nextInt();
    if(Math.abs(var4)%2 == 0){
      //value is even
      refVarA.setData(var3);
      refVarB.setData(var3);
    }else{
      //value is odd
      refVarA.setData(var3);
      refVarB.setData(var3 + var4);
    }//end else
    System.out.print(
        refVarA.equals(refVarB) + " ");
      
    if(Math.abs(var4)%2 != 0){
      //value is odd
      refVarA.setData(var3);
      refVarB.setData(var3);
    }else{
      //value is even
      refVarA.setData(var3);
      refVarB.setData(var3 + var4);
    }//end else
    System.out.println(
              refVarB.equals(refVarA));

  }//end main
}//end class Samp040  
//===================================//
  
class Samp040Class{
  private static int objCnt = 0;
  private int data;
  
  Samp040Class(){//constructor
    if(objCnt++ == 0){
      //Display name only for first 
      // object instantiated
      System.out.println("Samp040");
      System.out.println(
                   "Richard Baldwin");}
  }//end constructor
  
  void setData(int dataIn){
    data = dataIn;
  }//end setData()
  
  public boolean equals(
                Samp040Class objRefIn){
    return data == objRefIn.data;
  }//end overridden equals()

}//end class Samp040Class

Program Samp048.java
 
/*File Samp048 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
  Instantiating an abstract class is
    not allowed.
  Extending an abstract class.
  Parameterized constructor.
  Storing a ref to a subclass object in
    a ref var of a superclass type.
  Requirement to downcast a superclass
    ref variable to access a method in
    a subclass object.
  Overridden toString method.
  The this keyword.

The output consists of the following
five lines of text.  Because the 
program generates a random data value 
for testing, the actual values 
displayed will differ from one run to 
the next.

Samp048
Richard
Baldwin
23
23

**************************************/
import java.util.*;

//Note that this class is abstract
abstract class Samp048{
  public static void main(
                        String[] args){
                          
    //Following statement will not
    // compile.  Cannot instantiate an
    // abstract class
//  Samp048 refVar = new Samp048();

    Random rGen = new Random(
                 new Date().getTime());
    int ranNo = (byte)rGen.nextInt();

    //Note the superclass ref variable
    // type and the subclass object
    Samp048 refVar = 
               new Samp048Class(ranNo);
    System.out.println(refVar);
    
    //Note the following required cast
    System.out.println(
                ((Samp048Class)refVar).
                            getData());
    System.out.println(ranNo);
  }//end main
  
}//end class Samp048  
//===================================//
  
class Samp048Class extends Samp048{
  private int data;

  //constructor
  Samp048Class(int data){
    System.out.println("Samp048");
    System.out.println("Richard");
    this.data = data;
  }//end constructor
  
  public int getData(){
    return data;
  }//end getData()
  
  //overridden method - defined in the
  // Object class
  public String toString(){
    return "Baldwin";
  }//end overloaded toString()

}//end class Samp048Class

Program Samp050.java
 
/*File Samp050 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
  Extending an abstract class.
  Parameterized constructor.
  Defining an abstract method in the 
    superclass and overriding it in a 
    subclass to make it accessible 
    without a requirement to downcast 
    to the subclass type.
  Overridden toString method.

The output consists of the following
five lines of text.  Because the 
program generates a random data value 
for testing, the actual values 
displayed will differ from one run to 
the next.

Samp050
Richard
Baldwin
23
23

**************************************/
import java.util.*;

//Note that this class is abstract
abstract class Samp050{
  public static void main(
                        String[] args){
    Random rGen = new Random(
                 new Date().getTime());
    int ranNo = (byte)rGen.nextInt();

    //Note the superclass ref variable
    // type and the subclass object
    Samp050 refVar = 
               new Samp050Class(ranNo);
    System.out.println(refVar);
    System.out.println(
                     refVar.getData());
    System.out.println(ranNo);
  }//end main
  
  //Note the following abstract method
  // that is overridden in the subclass
  public abstract int getData();
  
}//end class Samp050  
//===================================//
  
class Samp050Class extends Samp050{
  private int data;

  //constructor
  Samp050Class(int inData){
    System.out.println("Samp050");
    System.out.println("Richard");
    data = inData;
  }//end constructor
  
  //overridden method - abstract in the
  // supeclass
  public int getData(){
    return data;
  }//end getData()
  
  //overridden method - defined in the
  // Object class
  public String toString(){
    return "Baldwin";
  }//end overloaded toString()

}//end class Samp050Class

Program Samp056.java
 
/*File Samp056 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
  Downcasting object ref in order to
  access a method belonging to the 
  object.

The output consists of the following 
two lines of text.

Samp056
Hello from Baldwin

**************************************/

import java.util.*;
class Samp056{
  public static void main(
                        String[] args){
    
    //Store ref to subclass object in
    // ref var of superclass type   
    Samp056 var = 
           new Samp056Class("Baldwin");
           
    //Following statement won't compile
//  var.sayHello();

    //Downcast the superclass ref to
    // the subclass type to invoke the
    // method.
    ((Samp056Class)var).sayHello();
    
  }//end main
}//end class Samp056  
//===================================//

class Samp056Class extends Samp056{
  private String data;

  Samp056Class(String data){
    System.out.println("Samp056");
    this.data = data;
  }//end constructor
    
  public void sayHello(){
    System.out.println(
                 "Hello from " + data);
  }//end sayHello()

}//end class Samp056Class

Program Samp058.java
 
/*File Samp058 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
  Instantiating anonymous object, and
    invoking method on that object.

The output consists of the following 
two lines of text.

Samp058
Hello from Baldwin

**************************************/

import java.util.*;
class Samp058{
  public static void main(
                        String[] args){
    //Instantiate anonymous object and
    // invoke method on that object. 
    new Samp058Class("Baldwin").
                            sayHello();

  }//end main
}//end class Samp058  
//===================================//

class Samp058Class{
  private String data;

  Samp058Class(String data){
    System.out.println("Samp058");
    this.data = data;
  }//end constructor
    
  public void sayHello(){
    System.out.println(
                 "Hello from " + data);
  }//end sayHello()

}//end class Samp058Class

Program Samp060.java
 
/*File Samp060 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
  Instantiating anonymous object, and
    invoking method on that object.
  Extending a class,
  Passing subclass object reference as 
    superclass type.
  Downcasting incoming object ref to 
    access method.

The output consists of the following 
five lines of text.  Because the 
program generates a random data value 
for testing, the actual values 
displayed will differ from one run to 
the next.

Samp060
Richard
Baldwin
78
78

**************************************/

import java.util.*;
class Samp060{
  public static void main(
                        String[] args){
   
    Random rGen = new Random(
                 new Date().getTime());
    int rNum = (byte)rGen.nextInt();

    //Note the following superclass
    // ref var holding ref to subclass
    // object.
    Samp060 objRef = 
               new Samp060ClassA(rNum);
               
    //Instantiate anonymous object,
    // invoke method on anonymous 
    // object passing superclass ref
    // var as parameter.
    System.out.println(
            new Samp060ClassB().
              getFromOtherObj(objRef));
    
    System.out.println(rNum);

  }//end main
}//end class Samp060  
//===================================//

  
class Samp060ClassA extends Samp060{
  private int data;

  Samp060ClassA(int data){
    System.out.println("Samp060");
    System.out.println("Richard");
    this.data = data;
  }//end constructor
    
  public int getData(){
    return data;
  }//end getData()

}//end class Samp060ClassA
//===================================//

class Samp060ClassB{

  Samp060ClassB(){
    System.out.println("Baldwin");
  }//end constructor
  
  public int getFromOtherObj(
                     Samp060 refToObj){
    //Note the required cast
    return ((Samp060ClassA)refToObj).
                             getData();
  }//end getFromOtherObj()

}//end class Samp060ClassB

Program Samp066.java
 
/*File Samp066 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
  Create and populate an array object
    without use of keyword new.

The output consists of the following
two lines of text: 

1 2 3 
Richard Baldwin

**************************************/

class Samp066{
  public static void main(
                        String[] args){
   
    //Create and populate array object
    // of type int without use of 
    // keyword new.
    int[] intArrayRef = {1,2,3};
    
    //Display contents of array 
    // elements
    for(int cnt=0;
               cnt<intArrayRef.length;
                                cnt++){
      System.out.print(
               intArrayRef[cnt] + " ");
    }//end for loop
    System.out.println();
    
    //Create and populate array object
    // of type Samp066Class without 
    // use of keyword new.
    Samp066Class[] objArrayRef = {
      new Samp066Class("Richard"),
      new Samp066Class("Baldwin")};

    //Display contents of array 
    // elements
    for(int cnt=0;
               cnt<objArrayRef.length;
                                cnt++){
      System.out.print(
            objArrayRef[cnt].getData() 
                                + " ");
    }//end for loop
    System.out.println();
    
  }//end main
}//end class Samp066  
//===================================//

class Samp066Class{
  private String data;

  Samp066Class(String data){
    this.data = data;
  }//end constructor
    
  public String getData(){
    return data;
  }//end getData()

}//end class Samp066Class

Program Samp068.java
 
/*File Samp068 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
  Create and populate an array object
    of type Object without use of 
    keyword new.
  Downcast object references when
    fetched from array to access 
    method.

The output consists of the following
line of text: 

Richard Baldwin

**************************************/

class Samp068{
  public static void main(
                        String[] args){
   
    //Create and populate array object
    // of type Object without use of 
    // keyword new.
    Object[] objArrayRef = {
      new Samp068Class("Richard"),
      new Samp068Class("Baldwin")};

    //Display contents of objects 
    // referred to by array elements
    for(int cnt=0;
               cnt<objArrayRef.length;
                                cnt++){
      //Following won't compile due to
      // need for downcast
//    System.out.print(
//          objArrayRef[cnt].getData() 
//                              + " ");
      System.out.print(((Samp068Class)
            objArrayRef[cnt]).getData()
                                + " ");
                                
    }//end for loop
    System.out.println();
    
  }//end main
}//end class Samp068  
//===================================//

class Samp068Class{
  private String data;

  Samp068Class(String data){
    this.data = data;
  }//end constructor
    
  public String getData(){
    return data;
  }//end getData()

}//end class Samp068Class

Program Samp070.java
 
/*File Samp070 
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
  Create one-element array of type 
    Object without use of keyword new.
  Populate array element with reference
    to object when array is created.
  Passing object reference as type 
    Object.
  Downcasting incoming object ref to 
    access method.
  

The output consists of the following 
five lines of text.  Because the 
program generates a random data value 
for testing, the actual values 
displayed will differ from one run to 
the next.

Samp070
Richard
Baldwin
78
78

**************************************/

import java.util.*;
class Samp070{
  public static void main(
                        String[] args){
   
    Random rGen = 
      new Random(new Date().getTime());
    int rNum = (byte)rGen.nextInt();

    //Create and populate one-element
    // array object without use of
    // keyword new.
    Object[] objRef = 
             {new Samp070ClassA(rNum)};

    //Create anonymous object and 
    // invoke method on it, passing
    // parameter as type Object.
    System.out.println(
         new Samp070ClassB().
           getFromOtherObj(objRef[0]));
           
    System.out.println(rNum);

  }//end main
}//end class Samp070  
//===================================//

  
class Samp070ClassA extends Samp070{
  private int data;

  Samp070ClassA(int data){
    System.out.println("Samp070");
    System.out.println("Richard");
    this.data = data;
  }//end constructor
    
  public int getData(){
    return data;
  }//end getData()

}//end class Samp070ClassA
//===================================//

class Samp070ClassB{

  Samp070ClassB(){
    System.out.println("Baldwin");
  }//end constructor
  
  //Note that incoming parameter is
  // type Object.
  public int getFromOtherObj(
                      Object refToObj){
                        
    //Downcast to get and return data
    // from another object.
    return ((Samp070ClassA)refToObj).
                             getData();
  }//end getFromOtherObj()

}//end class Samp070ClassB


Copyright 2001, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

-end-